来源: stackexchange

问:
How to get second value via c# StartsWith() method
```<code>string text = "Today is a good day for help. **David Diaz He went to school.  **David Diaz like apple. ";
</code>```

How to get how many times the text **David Diaz occurs in the string text?

UPDATED MY QUESTION

答:
Updated Answer:
It sounds like you want to find the number of times a substring exists in your text. For that, you'll want to use RegEx.Matches, as explained in this answer: https://stackoverflow.com/a/3016577/682840

or LINQ, as explained in this answer: https://stackoverflow.com/a/541994/682840

Original Answer:

.StartsWith returns true/false if the string begins with the search string you provide.  If you're wanting to know where a substring exists within your text, you'll need to use .IndexOf or a Regular Expression for more advanced scenarios.

IndexOf will return the location in the text where your provided search string starts (or -1 if it isn't found).

ContentLicense: CC BY-SA 3.0

Body:
string text = "Today is a good day for help. **David Diaz He went to school.  **David Diaz like apple. ";

How to get how many times the text **David Diaz occurs in the string text?

UPDATED MY QUESTION


问:
Animating a navigation bar color
I am trying to animate a change of color of a navigation bar when popping back to a previous controller. To give it some context, I have controller A which is a collectionView Controller and has an opaque navigation bar color set by:

```<code>self.navigationController?.navigationBar.barTintColor = UIColor.rgb(red: 244, green: 67, blue: 54)
self.navigationController?.navigationBar.tintColor = .white
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
self.navigationController?.navigationBar.isTranslucent = false
</code>```

Once a collectionViewCell is selected I push to the next controller, B, where the navigation bar is altered to become transparent:

```<code>self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
</code>```

When a user taps on the back arrow, I want the navigationBar to return to it's original colors. I have tried a simple UIView animation on the controller B's viewWillDissappear function, willMove(toParentViewController) and the viewWillAppear function on Controller A:

Here is the animation:

```<code>UIView.animate(withDuration: 0.5) {
   self.navigationController?.navigationBar.barTintColor = UIColor.rgb(red: 244, green: 67, blue: 54)
   self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
   self.navigationController?.navigationBar.shadowImage = nil
   self.navigationController?.navigationBar.isTranslucent = false
   self.navigationController?.navigationBar.layoutIfNeeded()
}
</code>```

After doing this I tried using a transition coordinator but got the same results:

```<code>guard let coordinator = self.transitionCoordinator else {
        return
    }

coordinator.animate(alongsideTransition: {
    [weak self] context in
   self?.navigationController?.navigationBar.barTintColor = UIColor.rgb(red: 244, green: 67, blue: 54)
   self?.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
   self?.navigationController?.navigationBar.shadowImage = nil
   self?.navigationController?.navigationBar.isTranslucent = false
   self?.navigationController?.navigationBar.layoutIfNeeded()
}, completion: nil)
</code>```

It seems that no matter what I try, or where I put the code I always end up with the same outcome. I am aware that the code is repetitive, but I was just trying to figure out why, so a lot of copying and pasting occurred.

From what I can tell, I think that it has something to do with the background view of the previous controller, but I am stumped, I seem to see a black screen before the animation under the navigation bar. Any help would be greatly appreciated.

Thanks

答:
Details

xCode 8.3.2, swift 3.1

Solution

```<code>override func viewWillAppear(_ animated: Bool) {
    if let navigationBar = self.navigationController?.navigationBar {
        navigationBar.backgroundColor = .blue
    }
}
</code>```

Full sample

ViewController

```<code>import UIKit

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.barTintColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1.0)
            navigationBar.tintColor = .white
            navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
            navigationBar.isTranslucent = false
        }
    }
}
</code>```

ViewController2

```<code>import UIKit

class ViewController2: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        if let navigationBar = self.navigationController?.navigationBar {
            let color = UIColor(red: 1, green: 153/255, blue: 0, alpha: 1.0)
            navigationBar.setBackgroundImage(UIImage.imageWithColor(color: color), for: .default)
            navigationBar.shadowImage = UIImage()
            navigationBar.isTranslucent = true
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.setBackgroundImage(nil, for: .default)
            navigationBar.shadowImage = nil
            navigationBar.isTranslucent = false
        }
    }
}
</code>```

extension UIImage

```<code>import UIKit

extension UIImage {
    class func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}
</code>```

Main.storyboard

```<code><?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12120" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="Tzy-ol-uu0">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackowerflow_44343355" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="eIC-Nm-Ex7">
                                <rect key="frame" x="164" y="318" width="46" height="30"/>
                                <state key="normal" title="Button"/>
                                <connections>
                                    <segue destination="QHs-H4-fAS" kind="show" id="Rff-Eq-K6g"/>
                                </connections>
                            </button>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="eIC-Nm-Ex7" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="G1g-VM-MAn"/>
                            <constraint firstItem="eIC-Nm-Ex7" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="mdZ-GP-EQw"/>
                        </constraints>
                    </view>
                    <navigationItem key="navigationItem" id="hq3-zt-U4K"/>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="977" y="791"/>
        </scene>
        <!--View Controller2-->
        <scene sceneID="F9C-Nz-6dd">
            <objects>
                <viewController id="QHs-H4-fAS" customClass="ViewController2" customModule="stackowerflow_44343355" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="AV0-X8-nhX"/>
                        <viewControllerLayoutGuide type="bottom" id="AsY-Gl-67v"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="1fA-pX-rzR">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="Uzd-Tb-KRO" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="1770" y="789"/>
        </scene>
        <!--Navigation Controller-->
        <scene sceneID="Jff-OO-3e7">
            <objects>
                <navigationController automaticallyAdjustsScrollViewInsets="NO" id="Tzy-ol-uu0" sceneMemberID="viewController">
                    <toolbarItems/>
                    <navigationBar key="navigationBar" contentMode="scaleToFill" id="804-YF-T6T">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
                        <autoresizingMask key="autoresizingMask"/>
                    </navigationBar>
                    <nil name="viewControllers"/>
                    <connections>
                        <segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="BRB-ym-7I2"/>
                    </connections>
                </navigationController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="M6i-ib-61I" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="140" y="791.15442278860576"/>
        </scene>
    </scenes>
</document>
</code>```

Title: Animating a navigation bar color

Body:
I am trying to animate a change of color of a navigation bar when popping back to a previous controller. To give it some context, I have controller A which is a collectionView Controller and has an opaque navigation bar color set by:

self.navigationController?.navigationBar.barTintColor = UIColor.rgb(red: 244, green: 67, blue: 54)
self.navigationController?.navigationBar.tintColor = .white
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
self.navigationController?.navigationBar.isTranslucent = false

Once a collectionViewCell is selected I push to the next controller, B, where the navigation bar is altered to become transparent:

self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true

When a user taps on the back arrow, I want the navigationBar to return to it's original colors. I have tried a simple UIView animation on the controller B's viewWillDissappear function, willMove(toParentViewController) and the viewWillAppear function on Controller A:

Here is the animation:

UIView.animate(withDuration: 0.5) {
   self.navigationController?.navigationBar.barTintColor = UIColor.rgb(red: 244, green: 67, blue: 54)
   self.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
   self.navigationController?.navigationBar.shadowImage = nil
   self.navigationController?.navigationBar.isTranslucent = false
   self.navigationController?.navigationBar.layoutIfNeeded()
}

After doing this I tried using a transition coordinator but got the same results:

guard let coordinator = self.transitionCoordinator else {
        return
    }

coordinator.animate(alongsideTransition: {
    [weak self] context in
   self?.navigationController?.navigationBar.barTintColor = UIColor.rgb(red: 244, green: 67, blue: 54)
   self?.navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
   self?.navigationController?.navigationBar.shadowImage = nil
   self?.navigationController?.navigationBar.isTranslucent = false
   self?.navigationController?.navigationBar.layoutIfNeeded()
}, completion: nil)

It seems that no matter what I try, or where I put the code I always end up with the same outcome. I am aware that the code is repetitive, but I was just trying to figure out why, so a lot of copying and pasting occurred.

From what I can tell, I think that it has something to do with the background view of the previous controller, but I am stumped, I seem to see a black screen before the animation under the navigation bar. Any help would be greatly appreciated.

Thanks

Body:
Details

xCode 8.3.2, swift 3.1

Solution

override func viewWillAppear(_ animated: Bool) {
    if let navigationBar = self.navigationController?.navigationBar {
        navigationBar.backgroundColor = .blue
    }
}

Full sample

ViewController

import UIKit

class ViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.barTintColor = UIColor(red: 244/255, green: 67/255, blue: 54/255, alpha: 1.0)
            navigationBar.tintColor = .white
            navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
            navigationBar.isTranslucent = false
        }
    }
}

ViewController2

import UIKit

class ViewController2: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        if let navigationBar = self.navigationController?.navigationBar {
            let color = UIColor(red: 1, green: 153/255, blue: 0, alpha: 1.0)
            navigationBar.setBackgroundImage(UIImage.imageWithColor(color: color), for: .default)
            navigationBar.shadowImage = UIImage()
            navigationBar.isTranslucent = true
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        if let navigationBar = self.navigationController?.navigationBar {
            navigationBar.setBackgroundImage(nil, for: .default)
            navigationBar.shadowImage = nil
            navigationBar.isTranslucent = false
        }
    }
}

extension UIImage

import UIKit

extension UIImage {
    class func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
        color.setFill()
        UIRectFill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

Main.storyboard

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12120" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="Tzy-ol-uu0">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackowerflow_44343355" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="eIC-Nm-Ex7">
                                <rect key="frame" x="164" y="318" width="46" height="30"/>
                                <state key="normal" title="Button"/>
                                <connections>
                                    <segue destination="QHs-H4-fAS" kind="show" id="Rff-Eq-K6g"/>
                                </connections>
                            </button>
                        </subviews>
                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="eIC-Nm-Ex7" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="G1g-VM-MAn"/>
                            <constraint firstItem="eIC-Nm-Ex7" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="mdZ-GP-EQw"/>
                        </constraints>
                    </view>
                    <navigationItem key="navigationItem" id="hq3-zt-U4K"/>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="977" y="791"/>
        </scene>
        <!--View Controller2-->
        <scene sceneID="F9C-Nz-6dd">
            <objects>
                <viewController id="QHs-H4-fAS" customClass="ViewController2" customModule="stackowerflow_44343355" customModuleProvider="target" sceneMemberID="viewController">
                    <layoutGuides>
                        <viewControllerLayoutGuide type="top" id="AV0-X8-nhX"/>
                        <viewControllerLayoutGuide type="bottom" id="AsY-Gl-67v"/>
                    </layoutGuides>
                    <view key="view" contentMode="scaleToFill" id="1fA-pX-rzR">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="Uzd-Tb-KRO" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="1770" y="789"/>
        </scene>
        <!--Navigation Controller-->
        <scene sceneID="Jff-OO-3e7">
            <objects>
                <navigationController automaticallyAdjustsScrollViewInsets="NO" id="Tzy-ol-uu0" sceneMemberID="viewController">
                    <toolbarItems/>
                    <navigationBar key="navigationBar" contentMode="scaleToFill" id="804-YF-T6T">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
                        <autoresizingMask key="autoresizingMask"/>
                    </navigationBar>
                    <nil name="viewControllers"/>
                    <connections>
                        <segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="BRB-ym-7I2"/>
                    </connections>
                </navigationController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="M6i-ib-61I" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="140" y="791.15442278860576"/>
        </scene>
    </scenes>
</document>


问:
How to redirect a WP page with this in the url.. ?page_id=xx
Trying to redirect a page that is here:

```<code>http://examplepage.com/?page_id=843&cs_search=1&c_=Carefree&s_=AZ
</code>```

There are several pages with the same page id of 843 that I would like to redirect to the home page.

I've tried a billion different solutions, but just can't quite figure it out.

thanks

答:
This should do the trick, and should catch only that single pageid:

```<code>RewriteEngine On
RewriteCond %{QUERY_STRING} ([&]|^)page_id=843([^\d]|$)
RewriteRule (.*) /? [R=301,L]
</code>```

?page_id=843 Redirected

?a=b&page_id=843 Redirected

?a=b&page_id=843&b=c Redirected

?a=b&aapage_id=843 NOT Redirected

?page_id=8435 NOT Redirected

ContentLicense: CC BY-SA 2.5

Body:
Trying to redirect a page that is here:

http://examplepage.com/?page_id=843&cs_search=1&c_=Carefree&s_=AZ

There are several pages with the same page id of 843 that I would like to redirect to the home page.

I've tried a billion different solutions, but just can't quite figure it out.

thanks

Body:
This should do the trick, and should catch only that single pageid:

RewriteEngine On
RewriteCond %{QUERY_STRING} ([&]|^)page_id=843([^\d]|$)
RewriteRule (.*) /? [R=301,L]

?page_id=843 Redirected

?a=b&page_id=843 Redirected

?a=b&page_id=843&b=c Redirected

?a=b&aapage_id=843 NOT Redirected

?page_id=8435 NOT Redirected


问:
How can I interpolate a variable from a command line argument into a string?
My program takes a command line argument which I would like to use to change the working directory of my Perl script.

```<code>use strict;
use warnings;
use Getopt::Std;
use Cwd 'chir';

my %opts=();
getopts('a:v:l:', \%opts);
my $application = $opts{a};
my $version = $opts{v};
my $location = $opts{l};

print "$application, $version, $location\n";

if($application eq 'abc') {
    #print "you came here\n";
    chdir "/viewstore/ccwww/dst_${application}_${version}/abc/${location}";
    print $ENV{PWD};
    print "you came here\n";
}
</code>```

I've previously tried with chdir '/var/tmp/dst_$application/$version/$location';, but that did not work either.

The current version of the code gives this warning.

Global symbol "$application_" requires explicit package name at ./test.pl line 20. Execution of ./test.pl aborted due to compilation errors.

Line 20 is the one with chdir.

答:
You are using single quotes '' in your chdir command. Single quotes do not do variable interpolation in Perl. That means that '/var/tmp/dst_$application/...' means /var/tmp/dst_$application/..., and not /var/tmp/dst_foo/....

You need to use double quotes "" to interpolate variables in strings.

```<code>chdir "/var/tmp/dst_$application/$version/$location";
</code>```

This will create /var/tmp/dst_foo/... instead.

If you need to separate a variable from the rest of the string, use this notation.

```<code>print "${foo}bar";
</code>```

This is different from "$foobar" because Perl thinks the whole $foobar is the variable name.

Body:
My program takes a command line argument which I would like to use to change the working directory of my Perl script.

use strict;
use warnings;
use Getopt::Std;
use Cwd 'chir';

my %opts=();
getopts('a:v:l:', \%opts);
my $application = $opts{a};
my $version = $opts{v};
my $location = $opts{l};

print "$application, $version, $location\n";

if($application eq 'abc') {
    #print "you came here\n";
    chdir "/viewstore/ccwww/dst_${application}_${version}/abc/${location}";
    print $ENV{PWD};
    print "you came here\n";
}

I've previously tried with chdir '/var/tmp/dst_$application/$version/$location';, but that did not work either.

The current version of the code gives this warning.

Global symbol "$application_" requires explicit package name at ./test.pl line 20. Execution of ./test.pl aborted due to compilation errors.

Line 20 is the one with chdir.

Body:
You are using single quotes '' in your chdir command. Single quotes do not do variable interpolation in Perl. That means that '/var/tmp/dst_$application/...' means /var/tmp/dst_$application/..., and not /var/tmp/dst_foo/....

You need to use double quotes "" to interpolate variables in strings.

chdir "/var/tmp/dst_$application/$version/$location";

This will create /var/tmp/dst_foo/... instead.

If you need to separate a variable from the rest of the string, use this notation.

print "${foo}bar";

This is different from "$foobar" because Perl thinks the whole $foobar is the variable name.


问:
Activity is NULL in fragment, but not always in Android
The this.getActivity() is NULL in my fragment, and is called from the actual activity itself.  This doesnt always happens but how can I fix this?

```<code>sportButton.setBackgroundColor(ViewHelper.getColor(this.getActivity()));
</code>```

EventActivity.java

```<code>eventsFragment.setUpEvents(getEventApplication());
</code>```

EventsFragment.java

```<code>public void setUpEvents(Application application) {
      sportButton.setBackgroundColor(ViewHelper.getColor(this.getActivity()));
</code>```

答:
If its fragment which runs inside a parent activity then in that case you can create a static Activity object in EventActivity and reference that in fragments instead of getActivity(), because its guaranteed to be available to the fragments.

EventActivity.class

```<code>protected Activity activity;

onResume()
{
    activity = this;
}
</code>```

EventsFragment.class

```<code>sportButton.setBackgroundColor(ViewHelper.getColor(EventActivity.activity));
</code>```

hope it helps

Body:
The this.getActivity() is NULL in my fragment, and is called from the actual activity itself.  This doesnt always happens but how can I fix this?

sportButton.setBackgroundColor(ViewHelper.getColor(this.getActivity()));

EventActivity.java

eventsFragment.setUpEvents(getEventApplication());

EventsFragment.java

public void setUpEvents(Application application) {
      sportButton.setBackgroundColor(ViewHelper.getColor(this.getActivity()));

Body:
If its fragment which runs inside a parent activity then in that case you can create a static Activity object in EventActivity and reference that in fragments instead of getActivity(), because its guaranteed to be available to the fragments.

EventActivity.class

protected Activity activity;

onResume()
{
    activity = this;
}

EventsFragment.class

sportButton.setBackgroundColor(ViewHelper.getColor(EventActivity.activity));

hope it helps


问:
How to read both Date and Time from a TDateTimePicker
I'm really confused. What I want to do (seems pretty simple) is to display a date + time in a TDateTimePicker, with the calendar integrated, and be able to read it after its value has changed.

I'd like to use the dd/MM/yyyy hh:mm format.

Since the TDateTimePicker isn't a TDateOrTimePicker, a used one with :

Kind : dtkDate (displays the calendar)

Format : 'dd/MM/yyyy hh:mm'

Looks good, now let's read it :

```<code>showmessage(DateTimeToStr(DateTimePicker1.Date));
</code>```

Only displays the date correctly. Changes on the hh:mm part is not taken into account. I always get the default value.
Then I thought : There is also a Time property, maybe I need to read the value in 2 times.

```<code> showmessage(DateTimeToStr(DateTimePicker1.Time));
 showmessage(DateTimeToStr(DateTimePicker1.Date));
</code>```

But I have the exact same output (and problem) as before. So now, let's try to change this Kind property to dtkTime, then read the time, then switch it back to dtkDate then read the date.

But no, it still doesn't work. Switching the Kind property from dtkDate to dtkTime erases my input on the hh:mm part.

I know I'm actually supposed to work with 2 TDateTimePickers : one for the date, one for the time.

So my question is :

Is there an easy way to solve my simple and very common problem (a
real DateTimePicker) ?

And a Delphi design questions :

Why is there a Format property that is basically useless and
misleading ? Having a TimeFormat, DateFormat, and proper format
validation process isn't that hard.

Please note that I post this question mainly to avoid beginners doing the same loooong process of debugging and frustration.

答:
I had the same frustrating problem these days. But in my case I just needed to get the complete Date and Time from the TDateTimePicker field (didn't needed to set it programatically, but it would not be very difficult). So what I did is to create my own TDateTimePicker and create a new public property that gets the field Caption and sets into DateTime (Caption is protected accordind to the documentation). Here's my code:

```<code>unit uZDateTimePicker;

interface

uses
 Vcl.ComCtrls, SysUtils;

type
  TZDateTimePicker = class(TDateTimePicker)
  private
    procedure SetDateAndTime;

  protected
    procedure Change; override;

  end;

implementation

{ TZDateTimePicker }

procedure TZDateTimePicker.Change;
begin
  SetDateAndTime
end;

procedure TZDateTimePicker.SetDateAndTime;
begin
  DateTime := StrToDateTime(Caption);
  inherited;
end;

end.
</code>```

As simple as that.

Also, if you use the DevExpress components you would use the TcxDateEdit that works just like you want.

Body:
I'm really confused. What I want to do (seems pretty simple) is to display a date + time in a TDateTimePicker, with the calendar integrated, and be able to read it after its value has changed.

I'd like to use the dd/MM/yyyy hh:mm format.

Since the TDateTimePicker isn't a TDateOrTimePicker, a used one with :

Kind : dtkDate (displays the calendar)

Format : 'dd/MM/yyyy hh:mm'

Looks good, now let's read it :

showmessage(DateTimeToStr(DateTimePicker1.Date));

Only displays the date correctly. Changes on the hh:mm part is not taken into account. I always get the default value.
Then I thought : There is also a Time property, maybe I need to read the value in 2 times.

 showmessage(DateTimeToStr(DateTimePicker1.Time));
 showmessage(DateTimeToStr(DateTimePicker1.Date));

But I have the exact same output (and problem) as before. So now, let's try to change this Kind property to dtkTime, then read the time, then switch it back to dtkDate then read the date.

But no, it still doesn't work. Switching the Kind property from dtkDate to dtkTime erases my input on the hh:mm part.

I know I'm actually supposed to work with 2 TDateTimePickers : one for the date, one for the time.

So my question is :

Is there an easy way to solve my simple and very common problem (a
real DateTimePicker) ?

And a Delphi design questions :

Why is there a Format property that is basically useless and
misleading ? Having a TimeFormat, DateFormat, and proper format
validation process isn't that hard.

Please note that I post this question mainly to avoid beginners doing the same loooong process of debugging and frustration.

Body:
I had the same frustrating problem these days. But in my case I just needed to get the complete Date and Time from the TDateTimePicker field (didn't needed to set it programatically, but it would not be very difficult). So what I did is to create my own TDateTimePicker and create a new public property that gets the field Caption and sets into DateTime (Caption is protected accordind to the documentation). Here's my code:

unit uZDateTimePicker;

interface

uses
 Vcl.ComCtrls, SysUtils;

type
  TZDateTimePicker = class(TDateTimePicker)
  private
    procedure SetDateAndTime;

  protected
    procedure Change; override;

  end;

implementation

{ TZDateTimePicker }

procedure TZDateTimePicker.Change;
begin
  SetDateAndTime
end;

procedure TZDateTimePicker.SetDateAndTime;
begin
  DateTime := StrToDateTime(Caption);
  inherited;
end;

end.

As simple as that.

Also, if you use the DevExpress components you would use the TcxDateEdit that works just like you want.


答:
By using StartWhith you can check if the string starts whit ** if it is take the first two words of the string whits will represent the name

```<code>        string text = "**David Diaz He went to school.";

        if (text.StartsWith("**"))
        {
            var names = text.Split(' ')
                .Take(2)
                .ToArray();
            var fullName = names[0] + " " + names[1];
        }
</code>```

UPDATE

As you said in the commend you want to look how many David Diaz occurs in one string, you can use regex for that.

```<code>  string text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";

        int matches = Regex.Matches(
            text,
            @"(?:\S+\s)?\S*David Diaz\S*(?:\s\S+)?",
            RegexOptions.IgnoreCase
        ).Count;
</code>```

Title: How to get second value via c# StartsWith() method

Body:
By using StartWhith you can check if the string starts whit ** if it is take the first two words of the string whits will represent the name

        string text = "**David Diaz He went to school.";

        if (text.StartsWith("**"))
        {
            var names = text.Split(' ')
                .Take(2)
                .ToArray();
            var fullName = names[0] + " " + names[1];
        }

UPDATE

As you said in the commend you want to look how many David Diaz occurs in one string, you can use regex for that.

  string text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";

        int matches = Regex.Matches(
            text,
            @"(?:\S+\s)?\S*David Diaz\S*(?:\s\S+)?",
            RegexOptions.IgnoreCase
        ).Count;


问:
How to add a class/id for a specific page in Wordpress?
I need a page that changes languages, depending on the URL. I'd like to add a class to an element when the URL contains en. For instance, example.com/en should show the page in English, while example.com shows the same page in Spanish.

How can I add or change a class in a div when I'm in example.com (Default language) and example.com/en (secondary language)?

答:
get_locale() gets the current language used on a page e.g. en_GB. See here for more details.

<div id="flag" class="<?php echo get_locale();?>">


问:
How do I set the style of a textView programmatically?
I'm creating a textView programmatically. Is there a way that i can set the style of this textView? Something similar to

```<code>style="@android:style/TextAppearance.DeviceDefault.Small"
</code>```

which I would use if I had a layout.xml file.

答:
Actually, this is possible as of API level 21.

TextView has a 4 parameter constructor:

```<code>TextView (Context context,
          AttributeSet attrs,
          int defStyleAttr,
          int defStyleRes)
</code>```

The middle two parameters are not necessary in this case. The following code creates a TextView directly in an activity and only defines its style resource:

```<code>TextView myStyledTextView = new TextView(this, null, 0, R.style.my_style);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a textView programmatically. Is there a way that i can set the style of this textView? Something similar to

style="@android:style/TextAppearance.DeviceDefault.Small"

which I would use if I had a layout.xml file.

Body:
Actually, this is possible as of API level 21.

TextView has a 4 parameter constructor:

TextView (Context context,
          AttributeSet attrs,
          int defStyleAttr,
          int defStyleRes)

The middle two parameters are not necessary in this case. The following code creates a TextView directly in an activity and only defines its style resource:

TextView myStyledTextView = new TextView(this, null, 0, R.style.my_style);


问:
JQuery slick carousel not loading, CDN loading error
New to JS and Jquery and having an issue getting slick to load with a bootstrap jumbotron. There are 4 background images with the following div's inside of .carousel but they are only loading in sequential order and I am getting an error in chrome inspect that claims the slick CDN is wrong even through it is copied straight from the website. Please let me know if you have any suggestions!

```<code><!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="./resource/reset.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/>
        <link rel="stylesheet" type="text/css" href="./resource/style.css">
        <link href="https://fonts.googleapis.com/css?family=Monoton|Open+Sans:400,600,700" rel="stylesheet">
        <link rel="icon" type="image/gif" href="./resource/favicon.png">
        <title>Jumpstart</title>
    </head>
<body>
    <!--Navigation Menu-->
    <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container">
            <ul class="nav navbar-nav">
                <li class="active"><a href="#">Explore</a></li>
                <li><a href="#">Start a Project</a></li>
                <li><a href="#">About Us</a></li>
            </ul>
        <img class="navbar-brand navbar-right collapse
        navbar-collapse visible-lg visible-md" src="./resource/images/logo.png" alt="Brand">
        </div>
    </nav>
    <!--Website Header with Scrolling Images-->
    <div class="carousel">
        <div class="jumbotron background jumbotron-bike">
            <div class="container-fluid">
                <h1>Get Going.</h1>
                <p>Jumpstart your startup with some crowdsourced seed money, or support one of our 300,000,000+ creators and get rewards.</p>
            </div>
        </div>
        <div class="jumbotron  background jumbotron-beer">
            <div class="container-fluid">
                <h1>GET THINKING.</h1>
                <p>Meet like-minded individuals who will help fuel your creative juices.</p>
            </div>
        </div>
        <div class="jumbotron background jumbotron-flowers">
            <div class="container-fluid">
                <h1>GET CREATING.</h1>
                <p>Stop overthinking projects and begin putting them out into the world.</p>
            </div>
        </div>
        <div class="jumbotron background jumbotron-duffel">
            <div class="container-fluid">
                <h1>GET STARTED.</h1>
                <p>What are you waiting for? Today's the day for your next big idea.</p>
            </div>
        </div>
    </div>
    <div class="relative-wrapper">
                <a href="#" class="btn btn-primary btn-lg">Jump In</a>
    </div>
    <!--Featured Project-->
    <div class="container featured-project">
       <div class="row">
            <h2 class="col-xs-12">Featured Project</h2>
        </div>
       <div class="row">
            <div class="col-xs-12 col-md-6">
                <div class="image-container">
                    <a href="#">
                        <img src="./resource/images/featured-project.png" alt="Featured Project" class="thumbnail">
                    </a>
                </div>
            </div>
            <div class="col-xs-6 col-md-3">
                <h3>Defrost: A Documentary</h3>
                <p>by Leo De Firenze</p>
                <p>"DeFrost is a documentary about growing up in a little red house in a cold, harsh valley.
                This is a story about my mother's childhood. This film attempts to capture vignettes of her upbringing â€” her family,
                friends, pets, and eventual depature from a freezing valley in Northern Italy â€” through beautiful cinematography and narration."
                </p>
            </div>
            <div class="col-xs-6 col-md-3 ">
                <h3>Product Categories</h3>
                <ul>
                    <li>Art</li>
                    <li>Books</li>
                    <li>Crystals</li>
                    <li>Design</li>
                    <li>Doodles</li>
                    <li>Deedlybobs</li>
                    <li>Farming</li>
                    <li>Gadgets</li>
                    <li>Hoverboards</li>
                    <li>Jams, Jellies, Etc.</li>
                    <li>Magazines</li>
                    <li>Plants</li>
                    <li>Snakes & Snake Equipment</li>
                    <li>Tables</li>
                    <li>Ventriliquist Figures</li>
                    <li>Yoyos</li>
                </ul>
            </div>
        </div>
    </div>
<!--Projects List-->
    <div class="container">
       <div class="row">
            <h2 class="col-xs-12">Projects</h2>
        </div>
        <div class="row">
            <div class="col-xs-12 col-sm-4 project">
                <div class="image-container">
                    <a href="#">
                        <img src="./resource/images/project1.png" alt="Proj1" class="thumbnail">
                    </a>
                </div>
                <h3>The Right Tights</h3>
                <p>by Riley Mae</p>
                <p>These tights are 50 denier, beautifully constructed,
                    hand-dyed, and guaranteed to last (no more ladders!). Made with high quality,
                    completely toxic-free materials. Custom colors available to all backers.
                </p>
            </div>
            <div class="col-xs-12 col-sm-4 project">
                <div class="image-container">
                    <a href="#">
                        <img src="./resource/images/project2.png" alt="Proj2" class="thumbnail">
                    </a>
                </div>
                <h3>Peppermint Smart Home</h3>
                <p>by Brian McDonald</p>
                <p>Instantly upgrade your home with technology that keeps your family and home safe.
                    We've made Peppermint easy to use. Just talk to your phone and Peppermint will help you every step of the way.
                </p>
            </div>
            <div class="col-xs-12 col-sm-4 project">
                <div class="image-container">
                    <a href="#">
                        <img src="./resource/images/project3.png" alt="Proj3" class="thumbnail">
                    </a>
                </div>
                <h3>American Streetlife</h3>
                <p>by Patrick Wallace</p>
                <p>I've been traveling around the United States for the past two years. I've slept on hundreds of couches,
                    more than a few benches, and captured my experiences in this 120 page photo album.
                </p>
            </div>
        </div>
    </div>
<!--Having Trouble Section-->
    <div class="container-fluid help">
        <strong>Having Trouble thinking of an idea?</strong>
        <p>Inventorsâ€™ block strikes at the worst times. But thatâ€™s
            all changed with Jumpstartâ€™s Good Idea Generator Lite (GIGLi).</p>
        <a href="#" class="btn btn-primary">Learn More</a>
    </div>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="crossorigin="anonymous"></script>
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js"></script>
    <script type="text/javascript" src="./resource/main.js"></script>
</body>
</html>'
</code>```

Here is the Jquery code:`$(document).ready(function () {

```<code> $('.carousel').slick({
        autoplay: true,
        autoplaySpeed: 4000,
        arrows: false,
        fade: true,
        pauseOnFocus: false,
        pauseOnHover: false,
        // slidesToShow: 1,
        slidesToScroll: 4
    });

    var scrol = 0;

});`
</code>```

It is also listed in a git repository to see it live here: https://github.com/solaini/Jumpstart

答:
Your code looks fine. Clear your cache & cookies and try loading the page again. If you still have the issue, try replacing:

//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js with ./resource/slick.min.js

//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css with ./resource/slick.css

Your code works good on my browser: see this.

Body:
New to JS and Jquery and having an issue getting slick to load with a bootstrap jumbotron. There are 4 background images with the following div's inside of .carousel but they are only loading in sequential order and I am getting an error in chrome inspect that claims the slick CDN is wrong even through it is copied straight from the website. Please let me know if you have any suggestions!

<!DOCTYPE html>

        <link rel="stylesheet" href="./resource/reset.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/>
        <link rel="stylesheet" type="text/css" href="./resource/style.css">
        <link href="https://fonts.googleapis.com/css?family=Monoton|Open+Sans:400,600,700" rel="stylesheet">
        <link rel="icon" type="image/gif" href="./resource/favicon.png">
        <title>Jumpstart</title>

Explore

Start a Project

About Us

Get Going.

Jumpstart your startup with some crowdsourced seed money, or support one of our 300,000,000+ creators and get rewards.

GET THINKING.

Meet like-minded individuals who will help fuel your creative juices.

GET CREATING.

Stop overthinking projects and begin putting them out into the world.

GET STARTED.

What are you waiting for? Today's the day for your next big idea.

                Jump In

Featured Project

Defrost: A Documentary

by Leo De Firenze

"DeFrost is a documentary about growing up in a little red house in a cold, harsh valley.
                This is a story about my mother's childhood. This film attempts to capture vignettes of her upbringing â€” her family,
                friends, pets, and eventual depature from a freezing valley in Northern Italy â€” through beautiful cinematography and narration."

Product Categories

Art

Books

Crystals

Design

Doodles

Deedlybobs

Farming

Gadgets

Hoverboards

Jams, Jellies, Etc.

Magazines

Plants

Snakes & Snake Equipment

Tables

Ventriliquist Figures

Yoyos

Projects

The Right Tights

by Riley Mae

These tights are 50 denier, beautifully constructed,
                    hand-dyed, and guaranteed to last (no more ladders!). Made with high quality,
                    completely toxic-free materials. Custom colors available to all backers.

Peppermint Smart Home

by Brian McDonald

Instantly upgrade your home with technology that keeps your family and home safe.
                    We've made Peppermint easy to use. Just talk to your phone and Peppermint will help you every step of the way.

American Streetlife

by Patrick Wallace

I've been traveling around the United States for the past two years. I've slept on hundreds of couches,
                    more than a few benches, and captured my experiences in this 120 page photo album.

        Having Trouble thinking of an idea?

Inventorsâ€™ block strikes at the worst times. But thatâ€™s
            all changed with Jumpstartâ€™s Good Idea Generator Lite (GIGLi).

        Learn More

'

Here is the Jquery code:`$(document).ready(function () {

 $('.carousel').slick({
        autoplay: true,
        autoplaySpeed: 4000,
        arrows: false,
        fade: true,
        pauseOnFocus: false,
        pauseOnHover: false,
        // slidesToShow: 1,
        slidesToScroll: 4
    });

    var scrol = 0;

});`

It is also listed in a git repository to see it live here: https://github.com/solaini/Jumpstart


问:
Android - sqlite gridview lag
I have done research but couldn't find a clear explanation, I know it has been asked before but I still don't have a solution.

I have a gridView that gets populated by sqlite. The problem is that the scroll of my gridView has lags. My code--

Adapter;

```<code>public class FoodListAdapter extends BaseAdapter {

private Context context;
private  int layout;
private ArrayList<Food> foodsList;

public FoodListAdapter(Context context, int layout, ArrayList<Food> foodsList) {
    this.context = context;
    this.layout = layout;
    this.foodsList = foodsList;
}

@Override
public int getCount() {
    return foodsList.size();
}

@Override
public Object getItem(int position) {
    return foodsList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

private class ViewHolder{
    CircularImageView imageView;
    TextView txtName, txtPrice;
}

@Override
public View getView(int position, View view, ViewGroup viewGroup) {

    View row = view;
    ViewHolder holder = new ViewHolder();

    if(row == null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(layout, null);

        holder.txtName = (TextView) row.findViewById(R.id.txtName);
        holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
        holder.imageView = (CircularImageView) row.findViewById(R.id.imgFood);
        row.setTag(holder);
    }
    else {
        holder = (ViewHolder) row.getTag();
    }

    Food food = foodsList.get(position);

    holder.txtName.setText(food.getName());
    holder.txtPrice.setText(food.getPrice());

    byte[] foodImage = food.getImage();
    Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
    holder.imageView.setImageBitmap(bitmap);

    return row;

}

}
</code>```

Activity;

```<code>public class FoodList extends AppCompatActivity {

GridView gridView;
ArrayList<Food> list;
AdapterView adapterView;
FoodListAdapter adapter = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.student_list_activity);

    sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);

    sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, price VARCHAR, image BLOB)");

    gridView = (GridView) findViewById(R.id.gridView);
    list = new ArrayList<>();
    adapter = new FoodListAdapter(this, R.layout.food_items, list);
    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            String dataFromGrid;
            dataFromGrid = ((TextView)(view.findViewById(R.id.txtName))).getText().toString();

            Intent i = new Intent(getApplicationContext(), FoodInfo.class);

            i.putExtra("unfromfood",dataFromGrid);
            startActivity(i);

        }
    });

    // get all data from sqlite
    Cursor cursor = sqLiteHelper.getData("SELECT * FROM FOOD");
    list.clear();
    while (cursor.moveToNext()){
        int id = cursor.getInt(0);
        String name = cursor.getString(1);
        String price = cursor.getString(2);
        byte[] image = cursor.getBlob(3);

        list.add(new Food(name, price, image, id));
    }
    adapter.notifyDataSetChanged();

}

@Override
public void onResume(){
    super.onResume();
    Cursor cursor = sqLiteHelper.getData("SELECT * FROM FOOD");
    list.clear();
    while (cursor.moveToNext()){
        int id = cursor.getInt(0);
        String name = cursor.getString(1);
        String price = cursor.getString(2);
        byte[] image = cursor.getBlob(3);

        list.add(new Food(name, price, image, id));
    }
    adapter.notifyDataSetChanged();

}

//Creating The Options Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

//Option Menu Click Events
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    // Settings
    if (id == R.id.action_add_student) {

        {
            final Intent intent = new Intent();
            intent.setClass(Student.this, MainActivity.class);
            startActivity(intent);
        }

    }

    return true;
}

}
</code>```

Everything works fine except the scrolling has lags, any help would be appreciated.

EDIT

```<code>public class AddFood extends AppCompatActivity {

EditText edtName, edtPrice;
Button btnChoose, btnAdd, btnList;
CircularImageView imageView;

final int REQUEST_CODE_GALLERY = 999;

public static SQLiteHelper sqLiteHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_food);

    init();

    sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);

    sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, price VARCHAR, image BLOB)");

    btnChoose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ActivityCompat.requestPermissions(
                    AddFood.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_CODE_GALLERY
            );
        }
    });

    //THIS IS WHERE I ADD

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try{
                sqLiteHelper.insertData(
                        edtName.getText().toString().trim(),
                        edtPrice.getText().toString().trim(),
                        imageViewToByte(imageView)
                );
                Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
                finish();
            }
            catch (Exception e){
                e.printStackTrace();
            }

        }
    });

}

private byte[] imageViewToByte(ImageView image) {
    Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if(requestCode == REQUEST_CODE_GALLERY){
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_CODE_GALLERY);
        }
        else {
            Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
        }
        return;
    }

    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null){
        Uri uri = data.getData();

        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            imageView.setImageBitmap(bitmap);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

private void init(){
    edtName = (EditText) findViewById(R.id.edtName);
    edtPrice = (EditText) findViewById(R.id.edtPrice);
    btnChoose = (Button) findViewById(R.id.btnChoose);
    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnList = (Button) findViewById(R.id.btnList);
    imageView = (CircularImageView) findViewById(R.id.imageView);
}

}
</code>```

答:
To get rid of the lag during scroll you have to load images efficiently. The best you can do is to use an image loading library like Glide.

Just import the library and replace these lines

```<code>byte[] foodImage = food.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
holder.imageView.setImageBitmap(bitmap);
</code>```

with this one

```<code>Glide.with(context)
    .load(food.getImage())
    .into(holder.imageView);
</code>```

I also suggest you read the Loading Large Bitmaps Efficiently

EDIT

In order to avoid the recycling issue (which in fact it's not an issue, it's the way a listview works) you have to check for each item if it has a photo or not.

If yes then load the image using Glide, else set to null (or a default image of your choice).

```<code>if (food.getImage() != null && food.getImage().length > 0) {
        Glide.with(context)
                .load(food.getImage())
                .into(holder.imageView);
    }
    else {
        holder.imageView.setImageBitmap(null); //or an image of your choice
    }
</code>```

Title: Android - sqlite gridview lag

Body:
I have done research but couldn't find a clear explanation, I know it has been asked before but I still don't have a solution.

I have a gridView that gets populated by sqlite. The problem is that the scroll of my gridView has lags. My code--

Adapter;

public class FoodListAdapter extends BaseAdapter {

private Context context;
private  int layout;
private ArrayList<Food> foodsList;

public FoodListAdapter(Context context, int layout, ArrayList<Food> foodsList) {
    this.context = context;
    this.layout = layout;
    this.foodsList = foodsList;
}

@Override
public int getCount() {
    return foodsList.size();
}

@Override
public Object getItem(int position) {
    return foodsList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

private class ViewHolder{
    CircularImageView imageView;
    TextView txtName, txtPrice;
}

@Override
public View getView(int position, View view, ViewGroup viewGroup) {

    View row = view;
    ViewHolder holder = new ViewHolder();

    if(row == null){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(layout, null);

        holder.txtName = (TextView) row.findViewById(R.id.txtName);
        holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
        holder.imageView = (CircularImageView) row.findViewById(R.id.imgFood);
        row.setTag(holder);
    }
    else {
        holder = (ViewHolder) row.getTag();
    }

    Food food = foodsList.get(position);

    holder.txtName.setText(food.getName());
    holder.txtPrice.setText(food.getPrice());

    byte[] foodImage = food.getImage();
    Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
    holder.imageView.setImageBitmap(bitmap);

    return row;

}

}

Activity;

public class FoodList extends AppCompatActivity {

GridView gridView;
ArrayList<Food> list;
AdapterView adapterView;
FoodListAdapter adapter = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.student_list_activity);

    sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);

    sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, price VARCHAR, image BLOB)");

    gridView = (GridView) findViewById(R.id.gridView);
    list = new ArrayList<>();
    adapter = new FoodListAdapter(this, R.layout.food_items, list);
    gridView.setAdapter(adapter);

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            String dataFromGrid;
            dataFromGrid = ((TextView)(view.findViewById(R.id.txtName))).getText().toString();

            Intent i = new Intent(getApplicationContext(), FoodInfo.class);

            i.putExtra("unfromfood",dataFromGrid);
            startActivity(i);

        }
    });

    // get all data from sqlite
    Cursor cursor = sqLiteHelper.getData("SELECT * FROM FOOD");
    list.clear();
    while (cursor.moveToNext()){
        int id = cursor.getInt(0);
        String name = cursor.getString(1);
        String price = cursor.getString(2);
        byte[] image = cursor.getBlob(3);

        list.add(new Food(name, price, image, id));
    }
    adapter.notifyDataSetChanged();

}

@Override
public void onResume(){
    super.onResume();
    Cursor cursor = sqLiteHelper.getData("SELECT * FROM FOOD");
    list.clear();
    while (cursor.moveToNext()){
        int id = cursor.getInt(0);
        String name = cursor.getString(1);
        String price = cursor.getString(2);
        byte[] image = cursor.getBlob(3);

        list.add(new Food(name, price, image, id));
    }
    adapter.notifyDataSetChanged();

}

//Creating The Options Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

//Option Menu Click Events
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    // Settings
    if (id == R.id.action_add_student) {

        {
            final Intent intent = new Intent();
            intent.setClass(Student.this, MainActivity.class);
            startActivity(intent);
        }

    }

    return true;
}

}

Everything works fine except the scrolling has lags, any help would be appreciated.

EDIT

public class AddFood extends AppCompatActivity {

EditText edtName, edtPrice;
Button btnChoose, btnAdd, btnList;
CircularImageView imageView;

final int REQUEST_CODE_GALLERY = 999;

public static SQLiteHelper sqLiteHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_food);

    init();

    sqLiteHelper = new SQLiteHelper(this, "FoodDB.sqlite", null, 1);

    sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS FOOD(Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, price VARCHAR, image BLOB)");

    btnChoose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ActivityCompat.requestPermissions(
                    AddFood.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_CODE_GALLERY
            );
        }
    });

    //THIS IS WHERE I ADD

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try{
                sqLiteHelper.insertData(
                        edtName.getText().toString().trim(),
                        edtPrice.getText().toString().trim(),
                        imageViewToByte(imageView)
                );
                Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
                finish();
            }
            catch (Exception e){
                e.printStackTrace();
            }

        }
    });

}

private byte[] imageViewToByte(ImageView image) {
    Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if(requestCode == REQUEST_CODE_GALLERY){
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_CODE_GALLERY);
        }
        else {
            Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
        }
        return;
    }

    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null){
        Uri uri = data.getData();

        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            imageView.setImageBitmap(bitmap);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

private void init(){
    edtName = (EditText) findViewById(R.id.edtName);
    edtPrice = (EditText) findViewById(R.id.edtPrice);
    btnChoose = (Button) findViewById(R.id.btnChoose);
    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnList = (Button) findViewById(R.id.btnList);
    imageView = (CircularImageView) findViewById(R.id.imageView);
}

}

Body:
To get rid of the lag during scroll you have to load images efficiently. The best you can do is to use an image loading library like Glide.

Just import the library and replace these lines

byte[] foodImage = food.getImage();
Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
holder.imageView.setImageBitmap(bitmap);

with this one

Glide.with(context)
    .load(food.getImage())
    .into(holder.imageView);

I also suggest you read the Loading Large Bitmaps Efficiently

EDIT

In order to avoid the recycling issue (which in fact it's not an issue, it's the way a listview works) you have to check for each item if it has a photo or not.

If yes then load the image using Glide, else set to null (or a default image of your choice).

if (food.getImage() != null && food.getImage().length > 0) {
        Glide.with(context)
                .load(food.getImage())
                .into(holder.imageView);
    }
    else {
        holder.imageView.setImageBitmap(null); //or an image of your choice
    }


问:
Socks 4 bind in php example
```<code><?php

error_reporting(E_ALL);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";

$result = socket_connect($socket, "92.51.77.126", 1080); // socks ip

if ($result === false)
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";

$in  = "\x04\x02";
$in .= "\x00\x50";  // http proxy port
$in .= "\xc0\xf0\x2e\x7e";  // http proxy ip address
$in .= "\x00";

socket_write($socket, $in, strlen($in));

sleep(1);

$in  = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";

socket_write($socket, $in, strlen($in));

$out = '';
while ($out = socket_read($socket, 2048)) {
    echo $out;
}

socket_close($socket);

?>
</code>```

I'd like to bind a socks 4 proxy server to connect an another proxy. This example the secound proxy is a http proxy. When connect the first is normally connected the server answer is Granted, but the communication at this time is finished. How continued the communication this example?

答:
You are lucky that you get a 'Granted' reply - I do not get any reply from SOCKS server in OpenSSH, it just closes the connection...

As I understand the SOCKS4 description, the answer for type 2 (BIND) request contains a port number and an IP address; when a connection arrives to them, your program will be able to read next status packet, which tells about the connection. There is a limited time (seems 2 minutes) of waiting for the connection. This is mainly for an FTP client - an FTP server needs back connection to the client and the BIND allows the connection to be passed.

If you want to initiate a connection from your side, use type 1 (CONNECT) request. Also, make sure the port and the IP address in the request are correct - seems in your code they are 80 and 192.240.30.126.

Title: Socks 4 bind in php example

Body:
<?php

error_reporting(E_ALL);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";

$result = socket_connect($socket, "92.51.77.126", 1080); // socks ip

if ($result === false)
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";

$in  = "\x04\x02";
$in .= "\x00\x50";  // http proxy port
$in .= "\xc0\xf0\x2e\x7e";  // http proxy ip address
$in .= "\x00";

socket_write($socket, $in, strlen($in));

sleep(1);

$in  = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";

socket_write($socket, $in, strlen($in));

$out = '';
while ($out = socket_read($socket, 2048)) {
    echo $out;
}

socket_close($socket);

?>

I'd like to bind a socks 4 proxy server to connect an another proxy. This example the secound proxy is a http proxy. When connect the first is normally connected the server answer is Granted, but the communication at this time is finished. How continued the communication this example?


问:
How to sort a data table items base on ID in C#?
I am new to C# and SQL and I am using windows forms.

As shown in the screenshot I am saving items to SQL table and then I read them to create buttons in flowLayoutPanel. The following code works fine but the problem is : when I read the items and add them to the flowLayoutPanel, they are added as they are in DataTable (unsorted).

Anyone knows how to add the buttons (Items) to flowLayoutPanel and re-order them based on their ID ? I mean I want to add them to flowLayoutPanel as : Item1 ,Item2, Item3, Item4 .

Thank you.

```<code>    SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
    SqlCommand MyCommand = new SqlCommand();
    DataTable DataTable = new DataTable();
    SqlDataAdapter Sql_Data_Adapter = new SqlDataAdapter();

                DataTable.Rows.Clear();
                DataTable.Columns.Clear();
                MyConnection.Open();
                MyCommand.CommandText = "SELECT * FROM Table_Items";
                MyCommand.Connection = MyConnection;
                Sql_Data_Adapter.SelectCommand = MyCommand;
                Sql_Data_Adapter.Fill(DataTable);

                MyCommand.Parameters.Clear();
                Sql_Data_Adapter.Dispose();
                MyConnection.Close();

                int RowIndex = DataTable.Rows.Count - 1;

                for (int i = 0; i <= RowIndex; i++)
                {

                    // create buttons

                    Button btn = new Button();

                    btn.Text = DataTable.Rows[i]"Item_Name"].ToString();
                    btn.Name = DataTable.Rows[i]["Item_Name"].ToString();

                    flowLayoutPanel1.Controls.Add(btn);

                }
</code>```

答:
Change your SQL Query to -</p>

```<code>SELECT * FROM Table_Items ORDER BY Id
</code>```

Body:
I am new to C# and SQL and I am using windows forms.

As shown in the screenshot I am saving items to SQL table and then I read them to create buttons in flowLayoutPanel. The following code works fine but the problem is : when I read the items and add them to the flowLayoutPanel, they are added as they are in DataTable (unsorted).

Anyone knows how to add the buttons (Items) to flowLayoutPanel and re-order them based on their ID ? I mean I want to add them to flowLayoutPanel as : Item1 ,Item2, Item3, Item4 .

Thank you.

    SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
    SqlCommand MyCommand = new SqlCommand();
    DataTable DataTable = new DataTable();
    SqlDataAdapter Sql_Data_Adapter = new SqlDataAdapter();

                DataTable.Rows.Clear();
                DataTable.Columns.Clear();
                MyConnection.Open();
                MyCommand.CommandText = "SELECT * FROM Table_Items";
                MyCommand.Connection = MyConnection;
                Sql_Data_Adapter.SelectCommand = MyCommand;
                Sql_Data_Adapter.Fill(DataTable);

                MyCommand.Parameters.Clear();
                Sql_Data_Adapter.Dispose();
                MyConnection.Close();

                int RowIndex = DataTable.Rows.Count - 1;

                for (int i = 0; i <= RowIndex; i++)
                {

                    // create buttons

                    Button btn = new Button();

                    btn.Text = DataTable.Rows[i]"Item_Name"].ToString();
                    btn.Name = DataTable.Rows[i]["Item_Name"].ToString();

                    flowLayoutPanel1.Controls.Add(btn);

                }

Body:
Change your SQL Query to -

SELECT * FROM Table_Items ORDER BY Id


问:
Set the table column width constant regardless of the amount of text in its cells?
In my table I set the width of the first cell in a column to be 100px.

However, when the text in one of the cell in this column is too long, the width of the column becomes more than 100px. How could I disable this expansion?

答:
Make the accepted answer respond for small screens when smaller than the fixed width.

HTML:

```<code><table>
  <tr>
    <th>header 1</th>
    <th>header 234567895678657</th>
  </tr>
  <tr>
    <td>data asdfasdfasdfasdfasdf</td>
    <td>data 2</td>
  </tr>
</table>
</code>```

CSS

```<code>table{
    border: 1px solid black;
    table-layout: fixed;
    max-width: 600px;
    width: 100%;
}

th, td {
    border: 1px solid black;
    overflow: hidden;
    max-width: 300px;
    width: 100%;
}
</code>```

JS Fiddle

https://jsfiddle.net/w9s3ebzt/

Body:
Make the accepted answer respond for small screens when smaller than the fixed width.

HTML:

<table>
  <tr>
    <th>header 1</th>
    <th>header 234567895678657</th>
  </tr>
  <tr>
    <td>data asdfasdfasdfasdfasdf</td>
    <td>data 2</td>
  </tr>
</table>

CSS

table{
    border: 1px solid black;
    table-layout: fixed;
    max-width: 600px;
    width: 100%;
}

th, td {
    border: 1px solid black;
    overflow: hidden;
    max-width: 300px;
    width: 100%;
}

JS Fiddle

https://jsfiddle.net/w9s3ebzt/


问:
RxJs getting original event inside subscribe without passing down
A little pseudo code to explain the title:

```<code>   Subject source = new Subject();

   function sendInNewResource(newNumber, anotherVariable) {
       source.next(newNumber);
   }

   const newSource = source
     .map((myNumber) => myNumber++);

   newSource.subscribe((data) => {
       //How can I access myObject here?
   });

   sendInNewResource(1, {myObject});
</code>```

I think the pseudo code explains a little of what I want to do.
So far, I've tried extending the observable, but if I did that it looks as though I'd need to override the operators within the observable.

I almost want to provide metadata to the event.

I do not want to pass the myObject down as this is a library for use externally, I will be subscribing to the observables within my codebase but chaining the observable will be done externally.

Anyone have any ideas on how to achieve this?

For context,
I'm trying to create a purely RxJs http library that will allow me to do the following:

```<code>const server$ = RxHttpServer(server)

const api$ = server.filter((request) => request.url.startsWith('/api'));

const apiEndpoint$ = api.map(() => ({
   status: 400,
   body: 'this is an api endpoint',
   headers: {
   }
}));

// Inside my library, note the use of the response object that I don't have access to:
apiEndpoint.subscribe((dataToSend) => response.write(dataToSend))
</code>```

The inner logic and handling of these objects has already been written, just need that response object to send back to.

答:
You could use a responseFor helper that would take the response metadata and return an observable of response Subjects, one for each HTTP request. The library user can subscribe it and write data to each response subject. While you, in the library, can subscribe to that same response subject and send it back to the client when it gets completed. Something like:

```<code>// even better extending the Observable prototype
// const apiEndpoint$ = api$.mapResponseFor(...
const apiEndpoint$ = api$.map(responseFor({
   status: 400,
   body: 'this is an api endpoint',
   headers: {}
}));

apiEndpoint$.subscribe(response => {
  response.next(data)
  response.complete()
})
</code>```

Body:
A little pseudo code to explain the title:

   Subject source = new Subject();

   function sendInNewResource(newNumber, anotherVariable) {
       source.next(newNumber);
   }

   const newSource = source
     .map((myNumber) => myNumber++);

   newSource.subscribe((data) => {
       //How can I access myObject here?
   });

   sendInNewResource(1, {myObject});

I think the pseudo code explains a little of what I want to do.
So far, I've tried extending the observable, but if I did that it looks as though I'd need to override the operators within the observable.

I almost want to provide metadata to the event.

I do not want to pass the myObject down as this is a library for use externally, I will be subscribing to the observables within my codebase but chaining the observable will be done externally.

Anyone have any ideas on how to achieve this?

For context,
I'm trying to create a purely RxJs http library that will allow me to do the following:

const server$ = RxHttpServer(server)

const api$ = server.filter((request) => request.url.startsWith('/api'));

const apiEndpoint$ = api.map(() => ({
   status: 400,
   body: 'this is an api endpoint',
   headers: {
   }
}));

// Inside my library, note the use of the response object that I don't have access to:
apiEndpoint.subscribe((dataToSend) => response.write(dataToSend))

The inner logic and handling of these objects has already been written, just need that response object to send back to.

Body:
You could use a responseFor helper that would take the response metadata and return an observable of response Subjects, one for each HTTP request. The library user can subscribe it and write data to each response subject. While you, in the library, can subscribe to that same response subject and send it back to the client when it gets completed. Something like:

// even better extending the Observable prototype
// const apiEndpoint$ = api$.mapResponseFor(...
const apiEndpoint$ = api$.map(responseFor({
   status: 400,
   body: 'this is an api endpoint',
   headers: {}
}));

apiEndpoint$.subscribe(response => {
  response.next(data)
  response.complete()
})


问:
UIImage color changing?
How can I change the UIImage's color through programming, any help please? If I send a UIImage, its color needs to change any help please? If I change the RGB color through bitmaphandling, it does not work.</p>

答:
Check out my post (mostly just remixing code).

Edit: This code basically creates a new CGContext, draws a layer on it with the new color, and returns a new UIImage from that. I haven't gone in depth on this code in a while, but it seems to just draw a UIImage with the same shape as the original, so that's a limit (loses any detail in the image).

Title: UIImage color changing?