问:
How to keep a div on the right side of the page in CSS
I'm building a website, and I'm trying to get a div element to stick to the right side of the page.

However, when my other divs, that contain blog post data/images scroll over to the next page, the div gets entered down.

How do I prevent the right side column from being entered down, while still allowing my blog post entries to scroll over?

Here is my code, what's relevant anyways. I'm sorry if this is a beginner question (it really is). I appreciate all the help I can get.
Thanks.

```<code>.column {
    float:left;
}

.column.main {
    width:70%;
    min-height:1px;
}

.column.side {
    width:20%;
    min-height:1px;

}

.column.left {
    width:10%;
    background-color:012C40;
    height:85%;
    min-width:1px;
}

.column.right {
    width:10%;
    background-color:012C40;
    height:85%;
    float:right;
    min-height:1px;
}

.postAd {
    width:19%;
    height:32%;
    float:left;
    background-color:DAEBF2;
    text-align:center;
    display:inline-block;
    margin:.5%;
    overflow: auto;
}

.postAd img {
    width:80%;
    height:80%;*/
}

<div class="column left">
</div>
<!--middle content-->

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">

    <img src="images/Sunset.JPG" alt="sunset">
    <p>Text here!</p>
</div>

<div class="postAd">
</div>

<!--right side content-->

<div class="column right">
</div>
</code>```

First of all, thanks for all of the proposed solutions! However, I've tried each one, and I'm running into problems. I have a navigation bar on top of my website, and each one overwrites that bar. When I try to make adaptations, I get the same problem as before. How do I implement these without completely destroying the layout of my website?

Again, huge thanks to everyone that responded.

答: You should use position: fixed; on the right div.</p>

Body:
I'm building a website, and I'm trying to get a div element to stick to the right side of the page.

However, when my other divs, that contain blog post data/images scroll over to the next page, the div gets entered down.

How do I prevent the right side column from being entered down, while still allowing my blog post entries to scroll over?

Here is my code, what's relevant anyways. I'm sorry if this is a beginner question (it really is). I appreciate all the help I can get.
Thanks.

.column {
    float:left;
}

.column.main {
    width:70%;
    min-height:1px;
}

.column.side {
    width:20%;
    min-height:1px;

}

.column.left {
    width:10%;
    background-color:012C40;
    height:85%;
    min-width:1px;
}

.column.right {
    width:10%;
    background-color:012C40;
    height:85%;
    float:right;
    min-height:1px;
}

.postAd {
    width:19%;
    height:32%;
    float:left;
    background-color:DAEBF2;
    text-align:center;
    display:inline-block;
    margin:.5%;
    overflow: auto;
}

.postAd img {
    width:80%;
    height:80%;*/
}

Text here!

Text here!

Text here!

Text here!

First of all, thanks for all of the proposed solutions! However, I've tried each one, and I'm running into problems. I have a navigation bar on top of my website, and each one overwrites that bar. When I try to make adaptations, I get the same problem as before. How do I implement these without completely destroying the layout of my website?

Again, huge thanks to everyone that responded.


来源: stackexchange

问:
How to parse data between  and
I want to parse the information between ...	 under Number of samples	.For example, after parsing the following html will return 64.

```<code>...
<tr class="border">
    <th>Average FPKM</th>
    <td colspan="2">0.8</td>
</tr>
<tr class="border">
    <th>Number of samples</th>
    <td colspan="2">64</td>
</tr>
...
</code>```

How to get only return the value 64 here?

Thanks

答:
First give the table cell an id, for this example I chose tableCell

Using pure JavaScript and no jQuery, this code does exactly what you want

```<code>var value = document.getElementById("tableCell").innerHTML
</code>```

Using jQuery you can do this:

```<code>var value = $("#tableCell").html()
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to parse data between <td colspan="2"> and </td>

Body:
I want to parse the information between ...	 under Number of samples	.For example, after parsing the following html will return 64.

...

    Average FPKM
    0.8

    Number of samples
    64

...

How to get only return the value 64 here?

Thanks

Body:
First give the table cell an id, for this example I chose tableCell

Using pure JavaScript and no jQuery, this code does exactly what you want

var value = document.getElementById("tableCell").innerHTML

Using jQuery you can do this:

var value = $("#tableCell").html()


问:
Passing target variables from pattern match to static
I'm writing a Makefile to wrap the deployment of an elastic beanstalk app to multiple environments. This is my first time writing an "advanced" makefile and I'm having a bit of trouble.

My goals are as follows:

make deploy by itself should deploy with ENVIRONMENT=$(USER) and ENV_TYPE=staging.

The environment to deploy to can be set via an environment variable. If ENVIRONMENT=production then ENV_TYPE=production, otherwise ENV_TYPE=staging.

As a shorthand for setting the environment variable, one can suffix the deploy target with a - and the name of the environment. For example: make deploy-production.

It's number 3 that is giving me the most trouble. Since any environment not named production is of type staging, I tried to use pattern matching to define the target for deploying to staging environments. Here's what I have currently:

```<code>ENVIRONMENT = $(USER)
ifeq ($ENVIRONMENT, production)
ENV_TYPE=production
else
ENV_TYPE=staging
endif
DOCKER_TAG ?= $(USER)
CONTAINER_PORT ?= 8000
ES_HOST = logging-ingest.$(ENV_TYPE).internal:80

.PHONY: deploy
deploy:
    -pip install --upgrade awsebcli
    sed "s/<<ES_HOST>>/$(ES_HOST)/" < 01-filebeat.template > .ebextensions/01-filebeat.config
    sed "s/<<DOCKER_TAG>>/$(DOCKER_TAG)/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/$(CONTAINER_PORT)/" > Dockerrun.aws.json
    eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
    eb deploy -v coolapp-$(ENVIRONMENT)

.PHONY: deploy-%
deploy-%: ENVIRONMENT=$*
deploy-%: deploy
    @echo  # Noop required

.PHONY: deploy-production
deploy-production: ENVIRONMENT=production
deploy-production: ENV_TYPE=production
deploy-production: deploy
    @echo  # Noop required
</code>```

The problem is in the last step of the deploy target. Namely, $(ENVIRONMENT) appears to be unset.

Example Output:

```<code>18:42 $ make -n deploy-staging
pip install --upgrade awsebcli
sed "s/<<ES_HOST>>/logging-ingest.staging.internal:80/" < 01-filebeat.template > .ebextensions/01-filebeat.config
sed "s/<<DOCKER_TAG>>/schultjo/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/8000/" > Dockerrun.aws.json
eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
eb deploy -v coolapp-
echo  # Noop required
</code>```

Desired Output:

```<code>18:42 $ make -n deploy-staging
pip install --upgrade awsebcli
sed "s/<<ES_HOST>>/logging-ingest.staging.internal:80/" < 01-filebeat.template > .ebextensions/01-filebeat.config
sed "s/<<DOCKER_TAG>>/schultjo/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/8000/" > Dockerrun.aws.json
eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
eb deploy -v coolapp-staging
echo  # Noop required
</code>```

So I have tried to implement Renaud's recursive Make solution, but have run into a minor hiccup. Here's a simplified Makefile that I'm using:

```<code>ENVIRONMENT ?= $(USER)
ifeq ($ENVIRONMENT, production)
ENV_TYPE = production
else
ENV_TYPE = staging
endif
ES_HOST = logging-ingest.$(ENV_TYPE).internal:80

.PHONY: deploy
deploy:
    @echo $(ENVIRONMENT)
    @echo $(ENV_TYPE)
    @echo $(ES_HOST)

.PHONY: deploy-%
deploy-%:
    @$(MAKE) --no-print-directory ENVIRONMENT=$* deploy
</code>```

When I run make production, it looks like the if statements surrounding the ENV_TYPE definition are not run again. Here's my actual output:

```<code>12:50 $ make -n deploy-production
/Applications/Xcode.app/Contents/Developer/usr/bin/make --no-print-directory ENVIRONMENT=production deploy
echo production
echo staging
echo logging-ingest.staging.internal:80
</code>```

The last two lines should say production rather than staging, implying there is something wrong with my conditional, but I haven't edited that conditional from earlier versions when it worked, so I'm a but confused. The same error happens if I invoke make with ENVIRONMENT set manually (e.g. ENVIRONMENT=production make deploy).

答:
Due to conversations w/@RenaudPacalet, I have learned that my approach mainly works because the variables defined in the deploy-% rules aren't used anywhere but the recipe...where they expand late, just before being passed to the shell.  This lets me use $* in the variable definition because the variable definition wont be expanded until the second phase, when $* actually has a value.

The method for setting ENV_TYPE uses a trick with patsubst to produce the condition for an if by stripping the word "production" from the content of $ENVIRONMENT; in this context, an empty string selects the else case.  So if $ENVIRONMENT is exactly equal to "production" then patsubst makes an empty string and the if evaluates to production, otherwise it evaluates to staging.

There's an explicit rule at the bottom for deploy- because that target would otherwise invoke some crazy implicit pattern rules that tried to compile deploy-.o

Finding that made me also consider the other error cases that could arise, so the first few lines define a function to ensure that, if a user specifies both ENVIRONMENT=X and uses a suffix Y, that there is an appropriate error message (rather than just having the suffix win).  You can see the call to that function as the first line of the deploy-% recipe.  There is another potential issue if $ENVIRONMENT is defined to have multiple words; the second deploy: line implements a test that will error out in this case---it tests that the word-count in $ENVIRONMENT is exactly 1 using the same patsubst/if trick as above.

It should also be noted that this makefile assumes the real work will be implemented in the recipe under deploy-%.

```<code># define a function to detect mismatch between ENV and suffix
ORIG_ENV := $(ENVIRONMENT)
ENV_CHECK = $(if $(ORIG_ENV),$(if $(subst $(ORIG_ENV),,$(ENVIRONMENT)),\
   $(error $$ENVIRONMENT differs from deploy-<suffix>.),),)

ENVIRONMENT ?= $(USER)

.PHONY: deploy
deploy: deploy-$(ENVIRONMENT)
deploy: $(if $(patsubst 1%,%,$(words $(ENVIRONMENT))),$(error Bad $$ENVIRONMENT: "$(ENVIRONMENT)"),)

.PHONY: deploy-%
deploy-%: ENVIRONMENT=$*
deploy-%: ENV_TYPE=$(if $(patsubst production%,%,$(ENVIRONMENT)),staging,production)
deploy-%:
        $(call ENV_CHECK)
        @echo  ENVIRONMENT: $(ENVIRONMENT)
        @echo  ENV_TYPE:    $(ENV_TYPE)

# keep it from going haywire if user specifies:
#   ENVIRONMENT= make deploy
# or
#   make deploy-
.PHONY: deploy-
deploy-:
        $(error Cannot build with empty $$ENVIRONMENT)
</code>```

Gives

```<code>$ USER=anonymous make deploy
ENVIRONMENT: anonymous
ENV_TYPE: staging

$ ENVIRONMENT=production make deploy
ENVIRONMENT: production
ENV_TYPE: production

$ ENVIRONMENT=test make deploy
ENVIRONMENT: test
ENV_TYPE: staging

$ make deploy-foo
ENVIRONMENT: foo
ENV_TYPE: staging

$ make deploy-production
ENVIRONMENT: production
ENV_TYPE: production

$ ENVIRONMENT=foo make deploy-production
Makefile:14: *** $ENVIRONMENT differs from deploy-<suffix>..  Stop.

$ ENVIRONMENT= make deploy
Makefile:24: *** Bad $ENVIRONMENT: "".  Stop.

$ make deploy-
Makefile:24: *** Cannot build with empty $ENVIRONMENT.  Stop.

$ ENVIRONMENT="the more the merrier" make deploy
Makefile:10: *** Bad $ENVIRONMENT: "the more the merrier".  Stop.
</code>```

Reflecting on how this works, it's not simple at all.  There are various interpretations of $ENVIRONMENT...for example in the line deploy: deploy-$(ENVIRONMENT), that sense of $ENVIRONMENT gets the one that comes in from the shell's environment (possibly being set to $(USER) if absent).  There's another sense in the recipe line @echo  ENVIRONMENT: $(ENVIRONMENT) which will be the one assigned in deploy-%: ENVIRONMENT=$* just above, but after expansion.  I am struck by the analogy with scoping or shadowing of variables in programming.

Body:
I'm writing a Makefile to wrap the deployment of an elastic beanstalk app to multiple environments. This is my first time writing an "advanced" makefile and I'm having a bit of trouble.

My goals are as follows:

make deploy by itself should deploy with ENVIRONMENT=$(USER) and ENV_TYPE=staging.

The environment to deploy to can be set via an environment variable. If ENVIRONMENT=production then ENV_TYPE=production, otherwise ENV_TYPE=staging.

As a shorthand for setting the environment variable, one can suffix the deploy target with a - and the name of the environment. For example: make deploy-production.

It's number 3 that is giving me the most trouble. Since any environment not named production is of type staging, I tried to use pattern matching to define the target for deploying to staging environments. Here's what I have currently:

ENVIRONMENT = $(USER)
ifeq ($ENVIRONMENT, production)
ENV_TYPE=production
else
ENV_TYPE=staging
endif
DOCKER_TAG ?= $(USER)
CONTAINER_PORT ?= 8000
ES_HOST = logging-ingest.$(ENV_TYPE).internal:80

.PHONY: deploy
deploy:
    -pip install --upgrade awsebcli
    sed "s/<<ES_HOST>>/$(ES_HOST)/" < 01-filebeat.template > .ebextensions/01-filebeat.config
    sed "s/<<DOCKER_TAG>>/$(DOCKER_TAG)/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/$(CONTAINER_PORT)/" > Dockerrun.aws.json
    eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
    eb deploy -v coolapp-$(ENVIRONMENT)

.PHONY: deploy-%
deploy-%: ENVIRONMENT=$*
deploy-%: deploy
    @echo  # Noop required

.PHONY: deploy-production
deploy-production: ENVIRONMENT=production
deploy-production: ENV_TYPE=production
deploy-production: deploy
    @echo  # Noop required

The problem is in the last step of the deploy target. Namely, $(ENVIRONMENT) appears to be unset.

Example Output:

18:42 $ make -n deploy-staging
pip install --upgrade awsebcli
sed "s/<<ES_HOST>>/logging-ingest.staging.internal:80/" < 01-filebeat.template > .ebextensions/01-filebeat.config
sed "s/<<DOCKER_TAG>>/schultjo/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/8000/" > Dockerrun.aws.json
eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
eb deploy -v coolapp-
echo  # Noop required

Desired Output:

18:42 $ make -n deploy-staging
pip install --upgrade awsebcli
sed "s/<<ES_HOST>>/logging-ingest.staging.internal:80/" < 01-filebeat.template > .ebextensions/01-filebeat.config
sed "s/<<DOCKER_TAG>>/schultjo/" < Dockerrun.template | sed "s/<<CONTAINER_PORT>>/8000/" > Dockerrun.aws.json
eb labs cleanup-versions --num-to-leave 10 --older-than 5 --force -v --region us-west-2
eb deploy -v coolapp-staging
echo  # Noop required

So I have tried to implement Renaud's recursive Make solution, but have run into a minor hiccup. Here's a simplified Makefile that I'm using:

ENVIRONMENT ?= $(USER)
ifeq ($ENVIRONMENT, production)
ENV_TYPE = production
else
ENV_TYPE = staging
endif
ES_HOST = logging-ingest.$(ENV_TYPE).internal:80

.PHONY: deploy
deploy:
    @echo $(ENVIRONMENT)
    @echo $(ENV_TYPE)
    @echo $(ES_HOST)

.PHONY: deploy-%
deploy-%:
    @$(MAKE) --no-print-directory ENVIRONMENT=$* deploy

When I run make production, it looks like the if statements surrounding the ENV_TYPE definition are not run again. Here's my actual output:

12:50 $ make -n deploy-production
/Applications/Xcode.app/Contents/Developer/usr/bin/make --no-print-directory ENVIRONMENT=production deploy
echo production
echo staging
echo logging-ingest.staging.internal:80

The last two lines should say production rather than staging, implying there is something wrong with my conditional, but I haven't edited that conditional from earlier versions when it worked, so I'm a but confused. The same error happens if I invoke make with ENVIRONMENT set manually (e.g. ENVIRONMENT=production make deploy).

Body:
Due to conversations w/@RenaudPacalet, I have learned that my approach mainly works because the variables defined in the deploy-% rules aren't used anywhere but the recipe...where they expand late, just before being passed to the shell.  This lets me use $* in the variable definition because the variable definition wont be expanded until the second phase, when $* actually has a value.

The method for setting ENV_TYPE uses a trick with patsubst to produce the condition for an if by stripping the word "production" from the content of $ENVIRONMENT; in this context, an empty string selects the else case.  So if $ENVIRONMENT is exactly equal to "production" then patsubst makes an empty string and the if evaluates to production, otherwise it evaluates to staging.

There's an explicit rule at the bottom for deploy- because that target would otherwise invoke some crazy implicit pattern rules that tried to compile deploy-.o

Finding that made me also consider the other error cases that could arise, so the first few lines define a function to ensure that, if a user specifies both ENVIRONMENT=X and uses a suffix Y, that there is an appropriate error message (rather than just having the suffix win).  You can see the call to that function as the first line of the deploy-% recipe.  There is another potential issue if $ENVIRONMENT is defined to have multiple words; the second deploy: line implements a test that will error out in this case---it tests that the word-count in $ENVIRONMENT is exactly 1 using the same patsubst/if trick as above.

It should also be noted that this makefile assumes the real work will be implemented in the recipe under deploy-%.

# define a function to detect mismatch between ENV and suffix
ORIG_ENV := $(ENVIRONMENT)
ENV_CHECK = $(if $(ORIG_ENV),$(if $(subst $(ORIG_ENV),,$(ENVIRONMENT)),\
   $(error $$ENVIRONMENT differs from deploy-<suffix>.),),)

ENVIRONMENT ?= $(USER)

.PHONY: deploy
deploy: deploy-$(ENVIRONMENT)
deploy: $(if $(patsubst 1%,%,$(words $(ENVIRONMENT))),$(error Bad $$ENVIRONMENT: "$(ENVIRONMENT)"),)

.PHONY: deploy-%
deploy-%: ENVIRONMENT=$*
deploy-%: ENV_TYPE=$(if $(patsubst production%,%,$(ENVIRONMENT)),staging,production)
deploy-%:
        $(call ENV_CHECK)
        @echo  ENVIRONMENT: $(ENVIRONMENT)
        @echo  ENV_TYPE:    $(ENV_TYPE)

# keep it from going haywire if user specifies:
#   ENVIRONMENT= make deploy
# or
#   make deploy-
.PHONY: deploy-
deploy-:
        $(error Cannot build with empty $$ENVIRONMENT)

Gives

$ USER=anonymous make deploy
ENVIRONMENT: anonymous
ENV_TYPE: staging

$ ENVIRONMENT=production make deploy
ENVIRONMENT: production
ENV_TYPE: production

$ ENVIRONMENT=test make deploy
ENVIRONMENT: test
ENV_TYPE: staging

$ make deploy-foo
ENVIRONMENT: foo
ENV_TYPE: staging

$ make deploy-production
ENVIRONMENT: production
ENV_TYPE: production

$ ENVIRONMENT=foo make deploy-production
Makefile:14: *** $ENVIRONMENT differs from deploy-<suffix>..  Stop.

$ ENVIRONMENT= make deploy
Makefile:24: *** Bad $ENVIRONMENT: "".  Stop.

$ make deploy-
Makefile:24: *** Cannot build with empty $ENVIRONMENT.  Stop.

$ ENVIRONMENT="the more the merrier" make deploy
Makefile:10: *** Bad $ENVIRONMENT: "the more the merrier".  Stop.

Reflecting on how this works, it's not simple at all.  There are various interpretations of $ENVIRONMENT...for example in the line deploy: deploy-$(ENVIRONMENT), that sense of $ENVIRONMENT gets the one that comes in from the shell's environment (possibly being set to $(USER) if absent).  There's another sense in the recipe line @echo  ENVIRONMENT: $(ENVIRONMENT) which will be the one assigned in deploy-%: ENVIRONMENT=$* just above, but after expansion.  I am struck by the analogy with scoping or shadowing of variables in programming.


问:
Compare date times in java in DAY hh:mm-hh:mm
How do we comapare dates and get the remainig available slots in java?

```<code>Sun 10:00-11:00
Sun 12:00-14:00
Sun 15:00-16:00
</code>```

So how can we get alll the availble time for a day in other than these three slots? how do we compare these dates in java? Can anyone please suggest?

答:
You can use compareTo method. Definition is that int java.util.Date.compareTo(Date anotherDate). Sample code is below:

```<code>    Calendar cal1 = Calendar.getInstance();
    cal1.set(2015, Calendar.JANUARY, 1);

    Calendar cal2 = Calendar.getInstance();
    cal2.set(2016, Calendar.JANUARY, 1);

    Date date1 = cal1.getTime();
    Date date2 = cal2.getTime();

    //Print -1, negative
    System.out.println(date1.compareTo(date2));

    cal1.set(2017, Calendar.JANUARY, 1);
    date1 = cal1.getTime();
    //Print 1, positive
    System.out.println(date1.compareTo(date2));

    cal1 = cal2;
    date1 = cal1.getTime();
    //Print 0, equal
    System.out.println(date1.compareTo(date2));
</code>```

Body:
How do we comapare dates and get the remainig available slots in java?

Sun 10:00-11:00
Sun 12:00-14:00
Sun 15:00-16:00

So how can we get alll the availble time for a day in other than these three slots? how do we compare these dates in java? Can anyone please suggest?

Body:
You can use compareTo method. Definition is that int java.util.Date.compareTo(Date anotherDate). Sample code is below:

    Calendar cal1 = Calendar.getInstance();
    cal1.set(2015, Calendar.JANUARY, 1);

    Calendar cal2 = Calendar.getInstance();
    cal2.set(2016, Calendar.JANUARY, 1);

    Date date1 = cal1.getTime();
    Date date2 = cal2.getTime();

    //Print -1, negative
    System.out.println(date1.compareTo(date2));

    cal1.set(2017, Calendar.JANUARY, 1);
    date1 = cal1.getTime();
    //Print 1, positive
    System.out.println(date1.compareTo(date2));

    cal1 = cal2;
    date1 = cal1.getTime();
    //Print 0, equal
    System.out.println(date1.compareTo(date2));


问:
Swift 3 Writing to Text File
In my application, I am trying to add data to a text file in the document directory of the program called saveURL.txt so it can later be called and parsed. I have my code being

```<code>let fileName = "saveURL"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")

let writeString = "Write this text to the fileURL as text in iOS using Swift"
do {
    // Write to the file
    try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
    print("past try writeString.write")
} catch let error as NSError {
    print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}

var readString = "" // Used to store the file contents
do {
    // Read the file contents
    readString = try String(contentsOf: fileURL)
} catch let error as NSError {
    print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("File Text: \(readString)")
</code>```

The output displayed in the console is

FilePath: /Users/mike/Library/Developer/CoreSimulator/Devices/752A5025-0AA0-4BE1-B70F-644A904F2D8A/data/Containers/Data/Application/0084AD99-63DB-439F-8427-DDDF161CFAC0/Documents/saveURL.txt

  past try writeString.write

  File Text: Write this text to the fileURL as text in iOS using Swift

Which is displaying output that it was infact stored, but when I go to check the file to see if it was actually appended to it, it is still blank. I've read all over that the swift files are meant to be read only and such but i've also seen examples that work but not in my program.

答:
Here is code for write url in your text file.

```<code>func writeToFile(urlString: String)
{
    let file = "/saveURL.txt" //this is the file. we will write to and read from it

        if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first {
        let path = dir + file
        print(path)
        do {
            try urlString.write(toFile: path, atomically: false, encoding: String.Encoding.utf8)
        }
        catch {/* error handling here */}
    }
}
</code>```

Hope this will help you.

Title: Swift 3 Writing to Text File

Body:
In my application, I am trying to add data to a text file in the document directory of the program called saveURL.txt so it can later be called and parsed. I have my code being

let fileName = "saveURL"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")

let writeString = "Write this text to the fileURL as text in iOS using Swift"
do {
    // Write to the file
    try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
    print("past try writeString.write")
} catch let error as NSError {
    print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}

var readString = "" // Used to store the file contents
do {
    // Read the file contents
    readString = try String(contentsOf: fileURL)
} catch let error as NSError {
    print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("File Text: \(readString)")

The output displayed in the console is

FilePath: /Users/mike/Library/Developer/CoreSimulator/Devices/752A5025-0AA0-4BE1-B70F-644A904F2D8A/data/Containers/Data/Application/0084AD99-63DB-439F-8427-DDDF161CFAC0/Documents/saveURL.txt

  past try writeString.write

  File Text: Write this text to the fileURL as text in iOS using Swift

Which is displaying output that it was infact stored, but when I go to check the file to see if it was actually appended to it, it is still blank. I've read all over that the swift files are meant to be read only and such but i've also seen examples that work but not in my program.

Body:
Here is code for write url in your text file.

func writeToFile(urlString: String)
{
    let file = "/saveURL.txt" //this is the file. we will write to and read from it

        if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first {
        let path = dir + file
        print(path)
        do {
            try urlString.write(toFile: path, atomically: false, encoding: String.Encoding.utf8)
        }
        catch {/* error handling here */}
    }
}

Hope this will help you.


问:
Url.Action fails to call controller method
I am trying to display some images on a page with this view

Details.cshtml

```<code>@foreach (var imagePath in Model.Images)
{
    <img src="@Url.Action("GetImage", "Receiving", new { @imagePath = imagePath })" />
}
</code>```

ReceivingController.cs

```<code>public ActionResult GetImage(string imagePath)
{
    var folder = ConfigurationManager.AppSettings["ImagesPath"];
    var path = Path.Combine(folder, imagePath);
    byte[] image = System.IO.File.ReadAllBytes(path);
    return File(image, "image/jpg");
}
</code>```

But when I set a breakpoint in the controller, it never gets hit and of course the images fail to load.

I can see the value being passed from the view is a path e.g. "C:\\inetpub\\wwwroot\\SiteName\\Images\\3000\\1\\1\\2.jpg"

I tried changing @Url.Action' to@Html.Action` just because I have no idea what else to try, but I got an error

OutputStream is not available when a custom TextWriter is used

I don't understand why the controller is not being called.

I noticed if I just navigate to the url Receiving\GetImage\whyareyounotworking, the controller action is fired.

I tried adding a route as below, but with no change

```<code>routes.MapRoute(
    name: "GetImage",
    url: "receiving/GetImage/{imagePath}",
    defaults: new { controller = "Receiving", action = "GetImage" }
);
</code>```

答:
It seems to be something to do with the string being passed in.

After removing the .jpg from the end of the file path before passing back to the controller my breakpoint now hits.

Body:
I am trying to display some images on a page with this view

Details.cshtml

@foreach (var imagePath in Model.Images)
{

}

ReceivingController.cs

public ActionResult GetImage(string imagePath)
{
    var folder = ConfigurationManager.AppSettings["ImagesPath"];
    var path = Path.Combine(folder, imagePath);
    byte[] image = System.IO.File.ReadAllBytes(path);
    return File(image, "image/jpg");
}

But when I set a breakpoint in the controller, it never gets hit and of course the images fail to load.

I can see the value being passed from the view is a path e.g. "C:\\inetpub\\wwwroot\\SiteName\\Images\\3000\\1\\1\\2.jpg"

I tried changing @Url.Action' to@Html.Action` just because I have no idea what else to try, but I got an error

OutputStream is not available when a custom TextWriter is used

I don't understand why the controller is not being called.

I noticed if I just navigate to the url Receiving\GetImage\whyareyounotworking, the controller action is fired.

I tried adding a route as below, but with no change

routes.MapRoute(
    name: "GetImage",
    url: "receiving/GetImage/{imagePath}",
    defaults: new { controller = "Receiving", action = "GetImage" }
);


问:
NSString Manipulation
I would like to manipulate the NSString like as

(0) Likes (1). (see. (2))

(0) =  Raman

(1) =  You

(2) = ThisGift

to

Raman Likes You. (see. ThisGift)

I dont know what approch can solve this problem.

Thanks in Advance,
Regards

Venkat.

答:
If you're allowed to change the template format, you can use format strings.

```<code>NSString *template1 = @"%1$@ Likes %2$@. (see. %3$@)",
         *template2 = @"%2$@ got a %3$@ from %1$@.";
NSString *msg1 = [NSString stringWithFormat:template1,@"Raman",@"You",@"ThisGift"],
         *msg2 = [NSString stringWithFormat:template2,@"Raman",@"You",@"ThisGift"];
</code>```

or (if the format string can always depend on the arguments being in replacement order):

```<code>NSString *template = @"%@ Likes %@. (see. %@)";
NSString *msg = [NSString stringWithFormat:template,@"Raman",@"You",@"ThisGift"];
</code>```

ContentLicense: CC BY-SA 2.5

Title: NSString Manipulation

Body:
If you're allowed to change the template format, you can use format strings.

NSString *template1 = @"%1$@ Likes %2$@. (see. %3$@)",
         *template2 = @"%2$@ got a %3$@ from %1$@.";
NSString *msg1 = [NSString stringWithFormat:template1,@"Raman",@"You",@"ThisGift"],
         *msg2 = [NSString stringWithFormat:template2,@"Raman",@"You",@"ThisGift"];

or (if the format string can always depend on the arguments being in replacement order):

NSString *template = @"%@ Likes %@. (see. %@)";
NSString *msg = [NSString stringWithFormat:template,@"Raman",@"You",@"ThisGift"];


问:
how to compress image without loosing its quality before uploading to database in php pdo mysql?
I'm presently working in online project..where users upload their images and that images will be first stored in server folder like "uploads" directory...and once the file will moved into that uploads directory..then the path will inserted into the mysql database using mysql query.
But the problem is..the images takes longer time to load on webpage...i want to reduce the image size before uploading into database and server..

here is my code

```<code>$upload_dir = 'user_images/'; // upload directory

        $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

        // valid image extensions
        $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

        // rename uploading image
        $userpic = rand(1000,1000000).".".$imgExt;

        // allow valid image file formats
        if(in_array($imgExt, $valid_extensions)){
            // Check file size '5MB'
            if($imgSize < 1000000){

                move_uploaded_file($tmp_dir,$upload_dir.$userpic);

            }
            else{
                $errMSG = "Sorry, your file is too large.";
            }
        }
        else{
            $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        }
    }
</code>```

And my query looks like..

```<code>if(!isset($errMSG))
    {

        $stmt = $user_home->runQuery("INSERT INTO cam_info (userID,
                                                            cam_name,
                                                cam_model,
                                            pixels,
                                    photoshoot,
                                    cam_rent,
                                    cam_img,
                                    mobile,
                                    state,
                                    address,
                                    upd_date,
                                    code )
                                                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");

        $stmt->bindParam(1,$id);
        $stmt->bindParam(2,$cam_name);
        $stmt->bindParam(3,$modelname);
        $stmt->bindParam(4,$pixel);
        $stmt->bindParam(5,$photoshoot);
        $stmt->bindParam(6,$rentpday);
        $stmt->bindParam(7,$userpic);
        $stmt->bindParam(8,$usermob);
        $stmt->bindParam(9,$state);
        $stmt->bindParam(10,$useraddrs);
        $stmt->bindParam(11,$upd_date);
        $stmt->bindParam(12,$ucode);

        if($stmt->execute())
        {

            $successMSG = "Record saved success";
        }
        else
        {
            $errMSG = "error while inserting....";
        }
</code>```

答:
Reduce the size is very general question as there are different aspects:

reduce the size on file system, ie bytes

reduce the size of dimension, ie pixels

To reduce the bytes you can:

apply compression - applicable on jpg, png.

convert the images in correct format - for screenshots is better png , for photos is better jpg

resize the image dimensions - for viewing and sending over the internet you do not need lot of mega pixels

reduce the number of colours

remove alpha channel if not used

remove EXIF information if not needed

To reduce the dimension:

consider the main media where the images will be viewed, ie mobile vs desktop

decide images max dimension of the image, up to 1024 px will be just fine to view on  most screens IMHO

Body:
I'm presently working in online project..where users upload their images and that images will be first stored in server folder like "uploads" directory...and once the file will moved into that uploads directory..then the path will inserted into the mysql database using mysql query.
But the problem is..the images takes longer time to load on webpage...i want to reduce the image size before uploading into database and server..

here is my code

$upload_dir = 'user_images/'; // upload directory

        $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

        // valid image extensions
        $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

        // rename uploading image
        $userpic = rand(1000,1000000).".".$imgExt;

        // allow valid image file formats
        if(in_array($imgExt, $valid_extensions)){
            // Check file size '5MB'
            if($imgSize < 1000000){

                move_uploaded_file($tmp_dir,$upload_dir.$userpic);

            }
            else{
                $errMSG = "Sorry, your file is too large.";
            }
        }
        else{
            $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        }
    }

And my query looks like..

if(!isset($errMSG))
    {

        $stmt = $user_home->runQuery("INSERT INTO cam_info (userID,
                                                            cam_name,
                                                cam_model,
                                            pixels,
                                    photoshoot,
                                    cam_rent,
                                    cam_img,
                                    mobile,
                                    state,
                                    address,
                                    upd_date,
                                    code )
                                                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");

        $stmt->bindParam(1,$id);
        $stmt->bindParam(2,$cam_name);
        $stmt->bindParam(3,$modelname);
        $stmt->bindParam(4,$pixel);
        $stmt->bindParam(5,$photoshoot);
        $stmt->bindParam(6,$rentpday);
        $stmt->bindParam(7,$userpic);
        $stmt->bindParam(8,$usermob);
        $stmt->bindParam(9,$state);
        $stmt->bindParam(10,$useraddrs);
        $stmt->bindParam(11,$upd_date);
        $stmt->bindParam(12,$ucode);

        if($stmt->execute())
        {

            $successMSG = "Record saved success";
        }
        else
        {
            $errMSG = "error while inserting....";
        }


问:
Bizarre Javascript JSON undefined error
I'm experiencing an error that I haven't been able to find any mention of anywhere. I'm developing an AJAX-enabled WCF web service with ASP.NET. In my ASP.NET master page's <asp:ScriptManager>, I included the json.js file, copied fresh from json.org. When I run the page, it fails (VS 2008 catches a Javascript exception) on the first line of code in json.js (following lots of comments), which is:

```<code>JSON = JSON || {};
</code>```

The error says that JSON is undefined:

Microsoft JScript runtime error: 'JSON' is undefined

Well, duh! That's why the line is testing if it's defined and if so setting it to an empty object! It is supposed to be undefined, right? Last I heard it was not an error in Javascript to perform such an operation on an undefined variable.

Can anyone give me a clue as to what's going on here? I suspect it's something gone wrong elsewhere that's somehow causing this problem. I don't have deep experience with either Javascript or ASP.NET so it might be that I'm missing some common gotcha in the setup.

答: I had the same problem trying to use google maps "streetview". The streetview window would turn completely black and I'd get the icon in the status bar indicating an error. I disabled DivX as webdev007 did and the problem was resolved! Webdev, you're a genius! Thanks! </p>

Title: Bizarre Javascript JSON undefined error

Body:
I'm experiencing an error that I haven't been able to find any mention of anywhere. I'm developing an AJAX-enabled WCF web service with ASP.NET. In my ASP.NET master page's <asp:ScriptManager>, I included the json.js file, copied fresh from json.org. When I run the page, it fails (VS 2008 catches a Javascript exception) on the first line of code in json.js (following lots of comments), which is:

JSON = JSON || {};

The error says that JSON is undefined:

Microsoft JScript runtime error: 'JSON' is undefined

Well, duh! That's why the line is testing if it's defined and if so setting it to an empty object! It is supposed to be undefined, right? Last I heard it was not an error in Javascript to perform such an operation on an undefined variable.

Can anyone give me a clue as to what's going on here? I suspect it's something gone wrong elsewhere that's somehow causing this problem. I don't have deep experience with either Javascript or ASP.NET so it might be that I'm missing some common gotcha in the setup.


问:
Create a folder in LocalFolder of UWP and copy files to it
I want to create folders dynamically and need to copy files to local folder of uwp app. Folder name should be the filename. For example if I upload a file with name Test01.png. Then a folder should create with name 'Test01' and need to copy Test01.png to Test01 folder. If the file already exist it should show alert like "file already exist,need to replace".</p>

```<code>        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.Desktop;

        foreach (string extension in FileExtensions.Video)
        {
            openPicker.FileTypeFilter.Add(extension);
        }

        file = await openPicker.PickSingleFileAsync();
        if (file != null)
        {
            StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            await ApplicationData.Current.LocalFolder.CreateFolderAsync("Data");//need to change the folder name with filename
            string desiredName = file.Name;
            //should copy it to subfolder and raise alert if already exist
            StorageFile newFile = await localFolder.CreateFileAsync(desiredName, CreationCollisionOption.FailIfExists);

        }
</code>```

答:
Here's what you could do. I've written this in notepad and did not get a chance to test this.</p>

```<code>FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;

foreach (string extension in FileExtensions.Video)
{
    openPicker.FileTypeFilter.Add(extension);
}

file = await openPicker.PickSingleFileAsync();
if (file != null)
{
    StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

    string folderName = System.IO.Path.GetFileNameWithoutExtension(file.Name);  //folder name with filename

    ////await ApplicationData.Current.LocalFolder.CreateFolderAsync("Data");//need to change the folder name with filename

    StorageFolder testFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("test", CreationCollisionOption.OpenIfExists);

    ////StorageFolder newFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);

    StorageFolder newFolder = await testFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);

    string desiredName = file.Name;
    //should copy it to subfolder and raise alert if already exist

    ////StorageFile newFile = await localFolder.CreateFileAsync(desiredName, CreationCollisionOption.FailIfExists);

    try
    {
        await file.CopyAsync(newFolder, desiredName, NameCollisionOption.FailIfExists);
    }
    catch(Exception exp)
    {
        //show here messagebox that is exists
        Windows.UI.Xaml.Controls.ContentDialog replacePromptDialog = new Windows.UI.Xaml.Controls.ContentDialog()
        {
            Title = "File exists in the new location",
            Content = "Do you want to replace the old file with the new file?",
            CloseButtonText = "Keep the old one",
            PrimaryButtonText = "Replace with new one"
        };
        Windows.UI.Xaml.Controls.ContentDialogResult result = await replacePromptDialog.ShowAsync();
        if (result == Windows.UI.Xaml.Controls.ContentDialogResult.Primary)
        {
            await file.CopyAsync(newFolder, desiredName, NameCollisionOption.ReplaceExisting);
        }
    }

}
</code>```

Body:
I want to create folders dynamically and need to copy files to local folder of uwp app. Folder name should be the filename. For example if I upload a file with name Test01.png. Then a folder should create with name 'Test01' and need to copy Test01.png to Test01 folder. If the file already exist it should show alert like "file already exist,need to replace".

        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.Desktop;

        foreach (string extension in FileExtensions.Video)
        {
            openPicker.FileTypeFilter.Add(extension);
        }

        file = await openPicker.PickSingleFileAsync();
        if (file != null)
        {
            StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            await ApplicationData.Current.LocalFolder.CreateFolderAsync("Data");//need to change the folder name with filename
            string desiredName = file.Name;
            //should copy it to subfolder and raise alert if already exist
            StorageFile newFile = await localFolder.CreateFileAsync(desiredName, CreationCollisionOption.FailIfExists);

        }

Body:
Here's what you could do. I've written this in notepad and did not get a chance to test this.

FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;

foreach (string extension in FileExtensions.Video)
{
    openPicker.FileTypeFilter.Add(extension);
}

file = await openPicker.PickSingleFileAsync();
if (file != null)
{
    StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

    string folderName = System.IO.Path.GetFileNameWithoutExtension(file.Name);  //folder name with filename

    ////await ApplicationData.Current.LocalFolder.CreateFolderAsync("Data");//need to change the folder name with filename

    StorageFolder testFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("test", CreationCollisionOption.OpenIfExists);

    ////StorageFolder newFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);

    StorageFolder newFolder = await testFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);

    string desiredName = file.Name;
    //should copy it to subfolder and raise alert if already exist

    ////StorageFile newFile = await localFolder.CreateFileAsync(desiredName, CreationCollisionOption.FailIfExists);

    try
    {
        await file.CopyAsync(newFolder, desiredName, NameCollisionOption.FailIfExists);
    }
    catch(Exception exp)
    {
        //show here messagebox that is exists
        Windows.UI.Xaml.Controls.ContentDialog replacePromptDialog = new Windows.UI.Xaml.Controls.ContentDialog()
        {
            Title = "File exists in the new location",
            Content = "Do you want to replace the old file with the new file?",
            CloseButtonText = "Keep the old one",
            PrimaryButtonText = "Replace with new one"
        };
        Windows.UI.Xaml.Controls.ContentDialogResult result = await replacePromptDialog.ShowAsync();
        if (result == Windows.UI.Xaml.Controls.ContentDialogResult.Primary)
        {
            await file.CopyAsync(newFolder, desiredName, NameCollisionOption.ReplaceExisting);
        }
    }

}


问:
calling function on Picker item Selection react native
I am trying to call a function whenever i select an item from picker and display the selected item with alert.

Here's what i am doing :-

```<code>import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
   constructor(props) {
  super(props);
  this.state = {
    isLoading: true,
    throttlemode:'',
  }
}
GetSelectedThrottleModeItem=(throttlemode)=>{
Alert.alert(this.state.throttlemode)
}
render() {
return (
    <View style={styles.MainContainerAddCamp}>
    <Text style={{fontSize: 12}}> Throttle Mode</Text>
    <Picker style={styles.PickerStyleClass}
  selectedValue={this.state.throttlemode}
  onValueChange={(throttlemodeValue, throttlemodeIndex) => this.GetSelectedThrottleModeItem(this.setState({throttlemode:throttlemodeValue}))}>
    <Picker.Item label="Asap" value="asap" />
    <Picker.Item label="Even" value="even" />
    </Picker>
   </View>
  );
}
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
    backgroundColor:'#87ceeb',
    paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
 borderColor: '#FF5722',
}
});
</code>```

This code is displaying the previously selected value. How can i make it to display current selected value.

Please suggest where i have missed.

答:
Alert is displaying the old value because it is being called before this.setState({throttlemode:throttlemodeValue}) is done. So the correct way of doing is

```<code>GetSelectedThrottleModeItem=(throttlemodeValue)=>{
Alert.alert(throttlemodeValue)
this.setState({throttlemode:throttlemodeValue})
}
render() {
 return (
  <View style={styles.MainContainerAddCamp}>
   <Text style={{fontSize: 12}}> Throttle Mode</Text>
   <Picker style={styles.PickerStyleClass}
    selectedValue={this.state.throttlemode}
    onValueChange={(throttlemodeValue, throttlemodeIndex) =>
    this.GetSelectedThrottleModeItem(throttlemodeValue)}>
    <Picker.Item label="Asap" value="asap" />
    <Picker.Item label="Even" value="even" />
   </Picker>
  </View>
 );
}
</code>```

Body:
I am trying to call a function whenever i select an item from picker and display the selected item with alert.

Here's what i am doing :-

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button,Platform,ActivityIndicator, Text, Picker, ScrollView } from 'react-native';
export default class FirstProject extends Component {
   constructor(props) {
  super(props);
  this.state = {
    isLoading: true,
    throttlemode:'',
  }
}
GetSelectedThrottleModeItem=(throttlemode)=>{
Alert.alert(this.state.throttlemode)
}
render() {
return (
    <View style={styles.MainContainerAddCamp}>
    <Text style={{fontSize: 12}}> Throttle Mode</Text>
    <Picker style={styles.PickerStyleClass}
  selectedValue={this.state.throttlemode}
  onValueChange={(throttlemodeValue, throttlemodeIndex) => this.GetSelectedThrottleModeItem(this.setState({throttlemode:throttlemodeValue}))}>
    <Picker.Item label="Asap" value="asap" />
    <Picker.Item label="Even" value="even" />
    </Picker>
   </View>
  );
}
}
const styles = StyleSheet.create({
MainContainerAddCamp :{
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 20,
padding: 5,
},
TextInputStyleClass: {
textAlign: 'left',
paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#00BCD4',
},
PickerStyleClass:{
    backgroundColor:'#87ceeb',
    paddingLeft: 7,
marginBottom: 7,
height: 40,
borderWidth: 1,
 borderColor: '#FF5722',
}
});

This code is displaying the previously selected value. How can i make it to display current selected value.

Please suggest where i have missed.

Body:
Alert is displaying the old value because it is being called before this.setState({throttlemode:throttlemodeValue}) is done. So the correct way of doing is

GetSelectedThrottleModeItem=(throttlemodeValue)=>{
Alert.alert(throttlemodeValue)
this.setState({throttlemode:throttlemodeValue})
}
render() {
 return (
  <View style={styles.MainContainerAddCamp}>
   <Text style={{fontSize: 12}}> Throttle Mode</Text>
   <Picker style={styles.PickerStyleClass}
    selectedValue={this.state.throttlemode}
    onValueChange={(throttlemodeValue, throttlemodeIndex) =>
    this.GetSelectedThrottleModeItem(throttlemodeValue)}>
    <Picker.Item label="Asap" value="asap" />
    <Picker.Item label="Even" value="even" />
   </Picker>
  </View>
 );
}


问:
adb is not recognized as an internal or exteral command error in Android studio
My application code is written and executed with no errors. However my emulator will not show up nor does my android device that's plugged in (virtualization is turned on, SDK packages are downloaded, Hyper V is not installed). I get this message from the ADB console:

```<code>adb is not recognized as an internal or exteral command, operable program or batch file.
</code>```

I have tried editing the %PATH% in both system and user variables but it never works.

I am using the latest Android studio and all the tutorials and answers to my problem refer to Eclipse. At this point I am wondering if I should just abandon Android studio and take refuge in the larger Eclipse community.

Can anyone advise me how to fix it? I've been already trying a long time and I would like to finally see my application in action.

答:
You've to set the adb.exe path location here.

You can find that, file>other setting>default project structure>{get your sdk file location}
Ex: C:\Users\Spectrum_Developer\AppData\Local\Android\Sdk

Open this path in file explorer and get into platform-tools. You can see adb.exe here.

Set this current path which is for ex. C:\Users\Spectrum_Developer\AppData\Local\Android\Sdk\platform-tools in your system environmental path variable

Restart the system.

Happy coding :-)

Body:
My application code is written and executed with no errors. However my emulator will not show up nor does my android device that's plugged in (virtualization is turned on, SDK packages are downloaded, Hyper V is not installed). I get this message from the ADB console:

adb is not recognized as an internal or exteral command, operable program or batch file.

I have tried editing the %PATH% in both system and user variables but it never works.

I am using the latest Android studio and all the tutorials and answers to my problem refer to Eclipse. At this point I am wondering if I should just abandon Android studio and take refuge in the larger Eclipse community.

Can anyone advise me how to fix it? I've been already trying a long time and I would like to finally see my application in action.


问:
How do I strip malicious HTML (XXS etc.) from content submissions?
I have a content submission form that contains multiple fields for input, all of which, when submitted, are entered directly into the database. When this content is requested, it is printed.

I have realized this is a security issue.

How can I strip malicious HTML (XSS) only, while still allowing formatting tags (b, i etc.)?

答:
There are several ways to handle this.

First off lets be clear: to do this in a secure manner, it cannot be done in javascript, only on the serverside - using javascript to securely enforce input sanitation is doomed to fail

Encode the chars that make up html when you output user generated data

When the user generated data is outputted on your webpage, change a few of the charachters to make it secure. Namely the characters <, > and & should be changed to <, > and & respectively.

This is the best way to do it, if the user should be allowed to edit the text, since you don't actually alter the text in storage, and you can let the user change the unmodified text via a textarea

Encode the chars that make up html when you store the user generated data

Do the same as above, but do it before you store the data in your db.

This has a performance upside, since you don't need to encode it every time you output it, but it will not let your users edit the unmodified text, which can be a serious downside, depending on what you are building

Strip the characters before output or storage

Strip the < and > characters before either output or storage - this is not a very good solution in my opinion, since it is an unnecessary altering of user input, but some people prefer it.

Body:
There are several ways to handle this.

First off lets be clear: to do this in a secure manner, it cannot be done in javascript, only on the serverside - using javascript to securely enforce input sanitation is doomed to fail

Encode the chars that make up html when you output user generated data

When the user generated data is outputted on your webpage, change a few of the charachters to make it secure. Namely the characters <, > and & should be changed to &lt;, &gt; and &amp; respectively.

This is the best way to do it, if the user should be allowed to edit the text, since you don't actually alter the text in storage, and you can let the user change the unmodified text via a textarea

Encode the chars that make up html when you store the user generated data

Do the same as above, but do it before you store the data in your db.

This has a performance upside, since you don't need to encode it every time you output it, but it will not let your users edit the unmodified text, which can be a serious downside, depending on what you are building

Strip the characters before output or storage

Strip the < and > characters before either output or storage - this is not a very good solution in my opinion, since it is an unnecessary altering of user input, but some people prefer it.


问:
Create a dataframe from a column in multiple excel file in R
I have some Excel files, each of them has a column named Distance; I want to put all the Distance columns into a dataframe; I have read them into R in the following way

```<code>file.list <- list.files(pattern = '*.xlsx')
df.list <- lapply(file.list, read_excel)
</code>```

Now in df.list I have 30 files and I want to create a dataframe containing the data in the form Distance1, Distance2, ..., Distance30 from df.list. Can anyone help me with this?

答:
In Hadleyverse approach:</p>

```<code>   library(purrr)
    d <- file.list %>% map(readxl::read_excel) %>% map("Distance") %>% set_names(nm = file.list) %>% dplyr::bind_cols()
</code>```

Body:
I have some Excel files, each of them has a column named Distance; I want to put all the Distance columns into a dataframe; I have read them into R in the following way

file.list <- list.files(pattern = '*.xlsx')
df.list <- lapply(file.list, read_excel)

Now in df.list I have 30 files and I want to create a dataframe containing the data in the form Distance1, Distance2, ..., Distance30 from df.list. Can anyone help me with this?

Body:
In Hadleyverse approach:

   library(purrr)
    d <- file.list %>% map(readxl::read_excel) %>% map("Distance") %>% set_names(nm = file.list) %>% dplyr::bind_cols()


问:
trying to implement my own stack object in DrRacket
Here is what I have so far, but I am unable to run it since there is an error so I don't know if it works, I am trying to create my own stack object using Object Oriented programming in DrRacket, I am using a dispatch method to call the different procedures I have if they are invoked properly.
For example first I would create a stack and then I would push and pop to the stack and also be able to print it.

```<code>(define (make-stack)
  (define my-stack '())

(define (pop)
 (define (pop-helper my-stack)
  (let ((result (car  my-stack))))
   (set!  my-stack (cdr  my-stack))
  result)
 (pop-helper  my-stack))

(define (push)
(define (push-helper x  my-stack)
  (set!  my-stack (cons x  my-stack)))
(push-helper x  my-stack))
(define (empty?)
 (define (empty-helper  my-stack)
   (if (null?  my-stack) #t
      #f))
  (empty-helper my-stack))
(define (print)
(define (print-helper  my-stack)
  (if (empty?) '()
      (print (cdr  my-stack))))
  (print-helper  my-stack))

(define (dispatch method)
(cond
  ((eq? method 'pop) pop)
  ((eq? method 'push) push)
  ((eq? method 'print) print)
  (else (lambda() (display "Unknown Request: ")(display method)(newline)))))
    dispatch)
</code>```

thanks in advance!

答:
You have a couple of syntax errors in two procedures, and you must not pass the stack as a parameter, it'll shadow the my-stack global variable. Here's the fix:

```<code>(define (pop)
  (let ((result (car my-stack))) ; `let` brackets were off
    (set! my-stack (cdr my-stack))
    result))

(define (push x) ; `x` parameter was missing
  (set! my-stack (cons x my-stack)))
</code>```

Body:
Here is what I have so far, but I am unable to run it since there is an error so I don't know if it works, I am trying to create my own stack object using Object Oriented programming in DrRacket, I am using a dispatch method to call the different procedures I have if they are invoked properly.
For example first I would create a stack and then I would push and pop to the stack and also be able to print it.

(define (make-stack)
  (define my-stack '())

(define (pop)
 (define (pop-helper my-stack)
  (let ((result (car  my-stack))))
   (set!  my-stack (cdr  my-stack))
  result)
 (pop-helper  my-stack))

(define (push)
(define (push-helper x  my-stack)
  (set!  my-stack (cons x  my-stack)))
(push-helper x  my-stack))
(define (empty?)
 (define (empty-helper  my-stack)
   (if (null?  my-stack) #t
      #f))
  (empty-helper my-stack))
(define (print)
(define (print-helper  my-stack)
  (if (empty?) '()
      (print (cdr  my-stack))))
  (print-helper  my-stack))

(define (dispatch method)
(cond
  ((eq? method 'pop) pop)
  ((eq? method 'push) push)
  ((eq? method 'print) print)
  (else (lambda() (display "Unknown Request: ")(display method)(newline)))))
    dispatch)

thanks in advance!

Body:
You have a couple of syntax errors in two procedures, and you must not pass the stack as a parameter, it'll shadow the my-stack global variable. Here's the fix:

(define (pop)
  (let ((result (car my-stack))) ; `let` brackets were off
    (set! my-stack (cdr my-stack))
    result))

(define (push x) ; `x` parameter was missing
  (set! my-stack (cons x my-stack)))


问:
Float left removes the hyperlinks
I know this is popular problem. I tried everything but still I could not make this work.
here is my html and css.

.unodered-item {
  float: left;
  overflow: hidden;
}
.item {
  height: 140px;
  width: 220px;
  margin-left: 10px;
  background: pink;
  //background-image: url("../resourses/tutorial-thumbnails/thumbnail.png");
  -webkit-background-size: cover;
  background-size: cover;
  overflow: hidden;
}

a.item-link {
  height: 140px;
  width: 220px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="recommended-list-items">
    <ul class="unodered unodered-recommended">
      <li class="unodered-item">
        <div class="item item'+ x +'">

        </div>
      </li>
    </ul>
</div></code>```

Help!!!

答:
It is not hidden. It is just empty. Add display: block to your a.item-link.

```<code>a.item-link {
    height: 140px;
    width: 220px;
    display: block;
}
</code>```

Title: Float left removes the hyperlinks

Body:
I know this is popular problem. I tried everything but still I could not make this work.
here is my html and css.

.unodered-item {
  float: left;
  overflow: hidden;
}
.item {
  height: 140px;
  width: 220px;
  margin-left: 10px;
  background: pink;
  //background-image: url("../resourses/tutorial-thumbnails/thumbnail.png");
  -webkit-background-size: cover;
  background-size: cover;
  overflow: hidden;
}

a.item-link {
  height: 140px;
  width: 220px;
}

Help!!!

Body:
It is not hidden. It is just empty. Add display: block to your a.item-link.

a.item-link {
    height: 140px;
    width: 220px;
    display: block;
}


问:
osascript command fails to Activate (open) “App Store app”.
I’m using MacOS 10.13, connected via SSH, running as the logged in user. When I run the following command:

```<code>osascript -e ‘tell application “App Store” to Activate’
</code>```

I’ve also tried:

```<code>open -a “App Store”
</code>```

Results in an error:

```<code>32:40: execution error: File permission error. (-54)
</code>```

This wasn’t a problem when using 10.12. Has something changed since the last update?

My end goal here is to open App Store via command line tool via SSH (ideally without using sudo command).

答:
You should use the correct quotation characters " (ASCII 0x22) and ' (ASCII 0x27):

```<code>osascript -e 'tell application "App Store" to activate'
</code>```

” (UTF-8 0xE2 0x80 0x9D) and ’ (UTF-8 0xE2 0x80 0x99) are not correct in AppleScript or Bash, respectively.

The same applies to the open command:

```<code>open -a 'App Store'
</code>```

or

```<code>open -a "App Store"
</code>```

Body:
I’m using MacOS 10.13, connected via SSH, running as the logged in user. When I run the following command:

osascript -e ‘tell application “App Store” to Activate’

I’ve also tried:

open -a “App Store”

Results in an error:

32:40: execution error: File permission error. (-54)

This wasn’t a problem when using 10.12. Has something changed since the last update?

My end goal here is to open App Store via command line tool via SSH (ideally without using sudo command).

Body:
You should use the correct quotation characters " (ASCII 0x22) and ' (ASCII 0x27):

osascript -e 'tell application "App Store" to activate'

” (UTF-8 0xE2 0x80 0x9D) and ’ (UTF-8 0xE2 0x80 0x99) are not correct in AppleScript or Bash, respectively.

The same applies to the open command:

open -a 'App Store'

or

open -a "App Store"


问:
JavaScript associative array behaving strangely
I have two objects. When I pass these as key to an associative array, and assign a value, all the values are stored wrong ( except for the last one ).

Can anyone please tell me what I'm doing wrong ??

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

var comm = {};

comm[usrMrid] = "ONE";
comm[usrXYZZ] = "TWO";

console.log("usrMrid: " + comm[usrMrid]); // this gives TWO, when it should give ONE
console.log("usrXYZZ: " + comm[usrXYZZ]); // this works fine```

答:
Object keys are String only! Use a Map for that:

```<code>var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

const comm = new Map([
  [usrMrid,"ONE"],
  [usrXYZZ, "TWO"]
]);

console.log(comm.get(usrMrid));
</code>```

However this is a really good usecase for Symbols too:

```<code> const id = Symbol("id");

var usrMrid = {
  name: "mrid",
  [id]:"ONE"
};
var usrXYZZ = {
   name: "xyzz",
    [id]:"TWO"
};

 console.log(usrMrid, usrMrid[id]);
</code>```

Body:
Object keys are String only! Use a Map for that:

var usrMrid = {name: "mrid"};
var usrXYZZ = {name: "xyzz"};

const comm = new Map([
  [usrMrid,"ONE"],
  [usrXYZZ, "TWO"]
]);

console.log(comm.get(usrMrid));

However this is a really good usecase for Symbols too:

 const id = Symbol("id");

var usrMrid = {
  name: "mrid",
  [id]:"ONE"
};
var usrXYZZ = {
   name: "xyzz",
    [id]:"TWO"
};

 console.log(usrMrid, usrMrid[id]);


问:
Calling HTML coding in JavaScript function using Spring framework
Can anyone tell me how can I call all my html coding using JavaScript in Spring framework without using any template engine such as Thymeleaf?</p>

答: What is purpose behind calling JS using spring-framework, any specific requirement. you can call JS methods and invoke this JS methods on body load while page rendering</p>


问:
Console calculator program in C++ not working correctly
I'm kind of new to programming in C++, and after a bit of learning how it works, I tried making this console calculator application, which takes in two numbers from the user x and y, and then adds, subtracts, multiplies or divides the two numbers depending on the third z input. I'm using code blocks as the IDE, and the code is as follows:

```<code>#include <iostream>

//First input value
int x;
//Second input value;
int y;
//Operator value;
int z;
int main()
{
    //Asks user for first number
    std::cout << "Input first number" << std::endl;
    std::cin >> x;
    std::cout << "" << std::endl;

    //Asks user for second number
    std::cout << "Input second number" << std::endl;
    std::cin >> y;
    std::cout << "" << std::endl;

    //Asks user for operation
    std::cout << "Input operation: 1 for add, 2 for sub, 3 for multiply, 4 for divide" << std::endl;
    std::cin >> z;

    //Displaying the desired output
    if (z = 1)
    {
        std::cout << x + y << std::endl;
    }
    else if (z = 2)
    {
        std::cout << x - y << std::endl;
    }
    else if (z = 3)
    {
        std::cout << x * y << std::endl;
    }
    else (z = 4);
    {
        std::cout << x / y << std::endl;
    }

    //Just a stupid comment
    std::cout << "Thank you for using this piece of shit xD. Press any key to end" << std::endl;
    return 0;
}
</code>```

Even though it compiles without any errors, every operation input seems to add the numbers together rather than the desired operation. Could anyone tell me what I'm doing wrong here?

答:
The value of this (z = 1) is always 1, which is practically true (as any other non-zero value would also be).

That is why you always end up in the first option.

A solution would probably be to use (z == 1).

Body:
I'm kind of new to programming in C++, and after a bit of learning how it works, I tried making this console calculator application, which takes in two numbers from the user x and y, and then adds, subtracts, multiplies or divides the two numbers depending on the third z input. I'm using code blocks as the IDE, and the code is as follows:

#include <iostream>

//First input value
int x;
//Second input value;
int y;
//Operator value;
int z;
int main()
{
    //Asks user for first number
    std::cout << "Input first number" << std::endl;
    std::cin >> x;
    std::cout << "" << std::endl;

    //Asks user for second number
    std::cout << "Input second number" << std::endl;
    std::cin >> y;
    std::cout << "" << std::endl;

    //Asks user for operation
    std::cout << "Input operation: 1 for add, 2 for sub, 3 for multiply, 4 for divide" << std::endl;
    std::cin >> z;

    //Displaying the desired output
    if (z = 1)
    {
        std::cout << x + y << std::endl;
    }
    else if (z = 2)
    {
        std::cout << x - y << std::endl;
    }
    else if (z = 3)
    {
        std::cout << x * y << std::endl;
    }
    else (z = 4);
    {
        std::cout << x / y << std::endl;
    }

    //Just a stupid comment
    std::cout << "Thank you for using this piece of shit xD. Press any key to end" << std::endl;
    return 0;
}

Even though it compiles without any errors, every operation input seems to add the numbers together rather than the desired operation. Could anyone tell me what I'm doing wrong here?


问:
How to use ARCore and ARkit in content page of the xamarin forms?
I want to implement augmented reality with xamarin forms. I found ARKit and ARCore library for xamarin.ios and xamarin.android respectively.

Can I use these both library in my PCL class library of xamarin.forms?

Can I integrate my page (layout or activity or UIViewController) to content page of my xamarin.forms?

Does renderer help to achieve the functionality?

答:
Can I use these both library in my PCL class library of xamarin.forms?

Most likely you can't. ARKit should be a native iOS library and ARCore is an Android library (Java)

Can I integrate my page (layout or activity or UIViewController) to content page of my xamarin.forms?

As far as I know not directly. You will need a custom renderer that will create the native view for your Xamarin.Forms view.

I'd suggest to have a look at Customizing a ContentPage.

The basic method is

Create a page type that is derived from ContentPage

Create custom renderers for each platform

Implement the OnElementChanged method

Create the native view

Add the native view with SetElement


问:
Hardware JPEG decompression / Win32
I know that most graphics hardware uses MPEG hardware decompression. I would like to use the hardware to decompress JPEG images. Does anyone know of a book or link to any information about using this functionality, or can tell me anything about it?

Also, I am willing to convert the images into a "video" if I can obtain hardware decompression of each frame. Would this be more viable?

答:
I don't agree to the "most graphics hardware uses MPEG hardware decompression", at least in the PC or similar desktop environment.

Mostly compression, decompression jobs are done in the main processor (CPU). Graphic hardwares mainly do the post processing of decompressed images.

MPEG decompression hardwares are extincted at least 10 years ago, I think.

Title: Hardware JPEG decompression / Win32


问:
Inplace insertion sort slower than insertion sort that creates a new list?
```<code>def insertion(sequence):
    for i in range(1, len(sequence)):
        key = sequence[i]
        j = search(sequence,0,i-1,key)
        while i > j:
            sequence[i], sequence[i-1] = sequence[i-1], sequence[i]
            i = i - 1
    return sequence

def insertion2(sequence):
    new_li = [sequence[0]]
    for i in range(1,len(sequence)):
        key = sequence[i]
        j = search(new_li,0,len(new_li)-1,key)
        new_li.insert(j,key)
    return new_li
</code>```

I have 2 insertions with 2 approaches. insertion is taking significantly longer than insertion2 (5.346 as compared to 0.0313). Need help figuring out why

PS: The search is basically an auxiliary function for binary search.

答:
You're doing a lot more work in the first one. When you find the insertion spot, you then continually swap items to move the item from [i] to [j] In the second, you're using the insert function to insert an item into the second array. That just moves everything in the array down by one.

Put another way, your insertion in the first does this:

```<code>while i > j
    temp = sequence[i]
    sequence[i] = sequence[i-1]
    sequence[i-1] = temp
    i = i-1
</code>```

So you do four array accesses and three assignments for every position the item has to move.

In the second one, the insert function does essentially this:

```<code>x = len(new_li)-1
while x < j
    new_li[i+1] = new_li[i]
    i = i - 1
</code>```

Here, you do only two array accesses and one assignment for each item you have to move.

You can speed this up by writing code that copies the item to be moved into a temp variable, and a loop that is essentially the same as the second loop I showed to move things from j to i down one space, and then drop the saved item into sequence[j].

Body:
def insertion(sequence):
    for i in range(1, len(sequence)):
        key = sequence[i]
        j = search(sequence,0,i-1,key)
        while i > j:
            sequence[i], sequence[i-1] = sequence[i-1], sequence[i]
            i = i - 1
    return sequence

def insertion2(sequence):
    new_li = [sequence[0]]
    for i in range(1,len(sequence)):
        key = sequence[i]
        j = search(new_li,0,len(new_li)-1,key)
        new_li.insert(j,key)
    return new_li

I have 2 insertions with 2 approaches. insertion is taking significantly longer than insertion2 (5.346 as compared to 0.0313). Need help figuring out why

PS: The search is basically an auxiliary function for binary search.

Body:
You're doing a lot more work in the first one. When you find the insertion spot, you then continually swap items to move the item from [i] to [j] In the second, you're using the insert function to insert an item into the second array. That just moves everything in the array down by one.

Put another way, your insertion in the first does this:

while i > j
    temp = sequence[i]
    sequence[i] = sequence[i-1]
    sequence[i-1] = temp
    i = i-1

So you do four array accesses and three assignments for every position the item has to move.

In the second one, the insert function does essentially this:

x = len(new_li)-1
while x < j
    new_li[i+1] = new_li[i]
    i = i - 1

Here, you do only two array accesses and one assignment for each item you have to move.

You can speed this up by writing code that copies the item to be moved into a temp variable, and a loop that is essentially the same as the second loop I showed to move things from j to i down one space, and then drop the saved item into sequence[j].


问:
Javascript - Resize two divs vertically on window resize
There are two divs vertically having unequal height. The minimum height of each div can be 40px.

When i resize the browser window, I want the divs to resize maintaining the aspect ratio.

I have created a demo in JSBIN. It works but it gets into Maximum call stack.

```<code>function divideEqually(h1, h2, diff) {
    let threshold = 40;
    let diffSplit = diff / 2;
    let leftOut1 = 0,
        leftOut2 = 0,
        leftOut = 0;

    if (h1 != threshold) {
        h1 = h1 + diffSplit;
    } else {
        leftOut1 = diffSplit;
    }
    if (h2 != threshold) {
        h2 = h2 + diffSplit;
    } else {
        leftOut2 = diffSplit;
    }

    diff = 0;
    if (h1 < threshold) {
        leftOut1 = threshold - h1;
        h1 = threshold;
    }
    if (h2 < threshold) {
        leftOut2 = threshold - h2;
        h2 = threshold;
    }

    diff = Math.ceil(leftOut1 + leftOut2);
    // error margin
    if (Math.abs(diff) > 0.5) {
        return divideEqually(h1, h2, diff);
    }
    return {
        h1: h1,
        h2: h2
    };
}

const qs = handle => document.querySelector(handle)
let initialHeight = window.innerHeight;

window.addEventListener('resize',()=>{
    const newHeight = window.innerHeight;
    const changeInHeight = newHeight - initialHeight;

    const h1 = qs("#top");
    const h2 = qs("#bottom")
    const h = divideEqually(h1.clientHeight,h2.clientHeight,changeInHeight);
    initialHeight = newHeight;

    h1.style.height = h.h1 + "px";
    h2.style.height = h.h2 + "px";

    // debug
    h1.innerHTML = h.h1;
    h2.innerHTML = h.h2;
})
</code>```

Is their any better way of doing this or optimising the function ?

答:
No need for Javascript; modern browsers have got you covered. Just add the flex property to the divs' CSS. This example gives the divs a 65/35 split.

#container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

#top {
  flex: 65 0 0%;
  min-height: 40px;
  width: 200px;
  background: red;
}

#bottom {
  flex: 35 0 0%;
  min-height: 40px;
  width: 200px;
  background: orange;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div id="top"></div>
  <div id="bottom"></div>
</div></code>```

Body:
There are two divs vertically having unequal height. The minimum height of each div can be 40px.

When i resize the browser window, I want the divs to resize maintaining the aspect ratio.

I have created a demo in JSBIN. It works but it gets into Maximum call stack.

function divideEqually(h1, h2, diff) {
    let threshold = 40;
    let diffSplit = diff / 2;
    let leftOut1 = 0,
        leftOut2 = 0,
        leftOut = 0;

    if (h1 != threshold) {
        h1 = h1 + diffSplit;
    } else {
        leftOut1 = diffSplit;
    }
    if (h2 != threshold) {
        h2 = h2 + diffSplit;
    } else {
        leftOut2 = diffSplit;
    }

    diff = 0;
    if (h1 < threshold) {
        leftOut1 = threshold - h1;
        h1 = threshold;
    }
    if (h2 < threshold) {
        leftOut2 = threshold - h2;
        h2 = threshold;
    }

    diff = Math.ceil(leftOut1 + leftOut2);
    // error margin
    if (Math.abs(diff) > 0.5) {
        return divideEqually(h1, h2, diff);
    }
    return {
        h1: h1,
        h2: h2
    };
}

const qs = handle => document.querySelector(handle)
let initialHeight = window.innerHeight;

window.addEventListener('resize',()=>{
    const newHeight = window.innerHeight;
    const changeInHeight = newHeight - initialHeight;

    const h1 = qs("#top");
    const h2 = qs("#bottom")
    const h = divideEqually(h1.clientHeight,h2.clientHeight,changeInHeight);
    initialHeight = newHeight;

    h1.style.height = h.h1 + "px";
    h2.style.height = h.h2 + "px";

    // debug
    h1.innerHTML = h.h1;
    h2.innerHTML = h.h2;
})

Is their any better way of doing this or optimising the function ?

Body:
No need for Javascript; modern browsers have got you covered. Just add the flex property to the divs' CSS. This example gives the divs a 65/35 split.

#container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

#top {
  flex: 65 0 0%;
  min-height: 40px;
  width: 200px;
  background: red;
}

#bottom {
  flex: 35 0 0%;
  min-height: 40px;
  width: 200px;
  background: orange;
}

<div id="container">
  <div id="top"></div>
  <div id="bottom"></div>
</div>


问:
How to handle empty URL parameter in react router dom (4.xx)
I have route defined as below :

```<code><Route path='/result/:searchTerm' component={Result}/>
</code>```

It works fine. For example localhost:3000/result/cat page works. But when the user decided to remove the :searchTerm from the URL and opens just localhost:3000/result/ it shows empty page. No errors or anything. Just empty page. It is not even hitting my component {Result} too.

So my doubt is how to handle this scenario.? Say I want to redirect the user who tries to open /result/ without :searchTerms to my index page.? How to do that.?

答:
I believe you can just add a question mark for an optional parameter, so:

```<code><Route path='/result/:searchTerm?' component={Result} />
</code>```

This works because React Router 4 uses path-to-regexp to interpret its path property.

To answer the last part of your question, you could simply test the value of :searchTerm and if it was undefined, redirect the user.

Body:
I have route defined as below :

<Route path='/result/:searchTerm' component={Result}/>

It works fine. For example localhost:3000/result/cat page works. But when the user decided to remove the :searchTerm from the URL and opens just localhost:3000/result/ it shows empty page. No errors or anything. Just empty page. It is not even hitting my component {Result} too.

So my doubt is how to handle this scenario.? Say I want to redirect the user who tries to open /result/ without :searchTerms to my index page.? How to do that.?

Body:
I believe you can just add a question mark for an optional parameter, so:

<Route path='/result/:searchTerm?' component={Result} />

This works because React Router 4 uses path-to-regexp to interpret its path property.

To answer the last part of your question, you could simply test the value of :searchTerm and if it was undefined, redirect the user.


问:
Cannot access value from case class
I am trying to use the sttp core library along with the sttp json4s library in order to receive a json response and convert it to a case class.

The source code on Github is here and the documentation for this example that I am trying to replicate is here

The response to the GET request to the URL http://httpbin.org/get?foo=bar looks like:

```<code>{
  "args": {
    "foo": "bar"
  },
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "Accept-Encoding": "gzip,deflate",
    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
    "Connection": "close",
    "Cookie": "_gauges_unique_day=1; _gauges_unique_month=1; _gauges_unique_year=1; _gauges_unique=1; stale_after=never",
    "Forwarded": "for=49.255.235.138",
    "Host": "httpbin.org",
    "Save-Data": "on",
    "Scheme": "http",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
  },
  "origin": "49.255.235.138, 66.249.82.79",
  "url": "http://httpbin.org/get?foo=bar"
}
</code>```

The case class which attempts to read the json response above looks like:

```<code>case class HttpBinResponse(
  args: Map[String, String],
  origin: String,
  headers: Map[String,String]
)
</code>```

The case class has been defined at the top of the test file and is accessible to the test.

This test passes:

```<code>it should "send a GET request parse response as JSON" in {
  implicit val backend = HttpURLConnectionBackend()
  val queryParams = Map("foo" -> "bar", "bugs" -> "life")

  val endpoint:Uri = uri"http://httpbin.org/get?foo=bar"

  val request = sttp
    .get(endpoint)
    .response(asJson[HttpBinResponse])

  val response = request.send()
  // response.body is an Either

  response.code should be(200)
  val res = response.body.fold(_ => { "Error" }, a => { a })

  res shouldBe a[HttpBinResponse]
}
</code>```

The code that produces the error looks like this:

```<code>it should "send a GET request parse response as JSON" in {
  implicit val backend = HttpURLConnectionBackend()

  val queryParams = Map("foo" -> "bar", "bugs" -> "life")

  val endpoint:Uri = uri"http://httpbin.org/get?foo=bar"

  val request = sttp
    .get(endpoint)
    .response(asJson[HttpBinResponse])

  val response = request.send()
  // response.body is an Either

  response.code should be(200)
  val res = response.body.fold(_ => { "Error" }, a => { a })

  res shouldBe a[HttpBinResponse]
  println(res.origin)
}
</code>```

However, when I try and access a value from the res.origin, I see the error that is value origin is not a member of java.io.Serializable

```<code>28. Waiting for source changes... (press enter to interrupt)
[info] Compiling 1 Scala source to /Users/localuser/Do/scalaexercises/target/scala-2.12/test-classes...
[error] /Users/localuser/Do/scalaexercises/src/test/scala/example/SttpSpec.scala:58: value origin is not a member of java.io.Serializable
[error]     println(res.origin)
[error]                 ^
[error] one error found
[error] (test:compileIncremental) Compilation failed
</code>```

答:
The question was answered by Rob Norris on the gitter scala channel as:

When you fold the Either the result is Serializable. Try pattern matching on it, or fold to sys.error instead of String.

Pattern Matching on the result:

```<code>val res = response.body.fold(_ => { "Error" }, a => { a })
res match {
  case HttpBinResponse(_, origin) => {
    println("-----------------------------")
    print("The origin for the request is ")
    print(origin)
    println("-----------------------------")
  }
  case _ => "Error"
}
</code>```

fold the Left to sys.error instead of String, no pattern matching needed in this case:

```<code>val res = response.body.fold(
  _ => { error("Error") },
  a => { a }
)
println(res.origin)
res.args should contain("foo" -> "bar")
res.args should contain key("bugs")
res.args should contain value("life")
res.origin.length should be >10
</code>```

Either of these two approaches would solve the issue.

Title: Cannot access value from case class

Body:
I am trying to use the sttp core library along with the sttp json4s library in order to receive a json response and convert it to a case class.

The source code on Github is here and the documentation for this example that I am trying to replicate is here

The response to the GET request to the URL http://httpbin.org/get?foo=bar looks like:

{
  "args": {
    "foo": "bar"
  },
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
    "Accept-Encoding": "gzip,deflate",
    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
    "Connection": "close",
    "Cookie": "_gauges_unique_day=1; _gauges_unique_month=1; _gauges_unique_year=1; _gauges_unique=1; stale_after=never",
    "Forwarded": "for=49.255.235.138",
    "Host": "httpbin.org",
    "Save-Data": "on",
    "Scheme": "http",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
  },
  "origin": "49.255.235.138, 66.249.82.79",
  "url": "http://httpbin.org/get?foo=bar"
}

The case class which attempts to read the json response above looks like:

case class HttpBinResponse(
  args: Map[String, String],
  origin: String,
  headers: Map[String,String]
)

The case class has been defined at the top of the test file and is accessible to the test.

This test passes:

it should "send a GET request parse response as JSON" in {
  implicit val backend = HttpURLConnectionBackend()
  val queryParams = Map("foo" -> "bar", "bugs" -> "life")

  val endpoint:Uri = uri"http://httpbin.org/get?foo=bar"

  val request = sttp
    .get(endpoint)
    .response(asJson[HttpBinResponse])

  val response = request.send()
  // response.body is an Either

  response.code should be(200)
  val res = response.body.fold(_ => { "Error" }, a => { a })

  res shouldBe a[HttpBinResponse]
}

The code that produces the error looks like this:

it should "send a GET request parse response as JSON" in {
  implicit val backend = HttpURLConnectionBackend()

  val queryParams = Map("foo" -> "bar", "bugs" -> "life")

  val endpoint:Uri = uri"http://httpbin.org/get?foo=bar"

  val request = sttp
    .get(endpoint)
    .response(asJson[HttpBinResponse])

  val response = request.send()
  // response.body is an Either

  response.code should be(200)
  val res = response.body.fold(_ => { "Error" }, a => { a })

  res shouldBe a[HttpBinResponse]
  println(res.origin)
}

However, when I try and access a value from the res.origin, I see the error that is value origin is not a member of java.io.Serializable

28. Waiting for source changes... (press enter to interrupt)
[info] Compiling 1 Scala source to /Users/localuser/Do/scalaexercises/target/scala-2.12/test-classes...
[error] /Users/localuser/Do/scalaexercises/src/test/scala/example/SttpSpec.scala:58: value origin is not a member of java.io.Serializable
[error]     println(res.origin)
[error]                 ^
[error] one error found
[error] (test:compileIncremental) Compilation failed

Body:
The question was answered by Rob Norris on the gitter scala channel as:

When you fold the Either the result is Serializable. Try pattern matching on it, or fold to sys.error instead of String.

Pattern Matching on the result:

val res = response.body.fold(_ => { "Error" }, a => { a })
res match {
  case HttpBinResponse(_, origin) => {
    println("-----------------------------")
    print("The origin for the request is ")
    print(origin)
    println("-----------------------------")
  }
  case _ => "Error"
}

fold the Left to sys.error instead of String, no pattern matching needed in this case:

val res = response.body.fold(
  _ => { error("Error") },
  a => { a }
)
println(res.origin)
res.args should contain("foo" -> "bar")
res.args should contain key("bugs")
res.args should contain value("life")
res.origin.length should be >10

Either of these two approaches would solve the issue.


问:
Filter on multiple columns in a table using one pipe in Angular

Hi everyone.
  I want to make a custom filter for my table which intakes more than one argument
  to search multiple columns .. in my case right now only one argument can be passed .
  thanks in advance

component.html

```<code><tr *ngFor = "let builder of builderDetailsArray[0] | filter :'groupName': searchString; let i = index" >
    <td style="text-align: center;"><mat-checkbox></mat-checkbox></td>
    <td>{{builder.builderId}}</td>
    <td>{{builder.viewDateAdded}}</td>
    <td>{{builder.viewLastEdit}}</td>
    <td>{{builder.groupName}}</td>
    <td>{{builder.companyPersonName}}</td>
    <td style="text-align: center;"><button mat-button color="primary">UPDATE</button></td>
</tr>
</code>```

pipe.ts

```<code>@Pipe({
    name: "filter",
    pure:false
})

export class FilterPipe implements PipeTransform {
    transform(items: any[], field: string, value: string): any[] {
    if (!items) {
        return [];
    }
    if (!field || !value) {
        return items;
    }
    return items.filter(singleItem =>
        singleItem[field].toLowerCase().includes(value.toLowerCase()) );
}
</code>```

答:
Created multiple arguments pipe in angular 4

The code lets you search through multiple columns in your table.

Passed 2 arguments in the transform function

value: Which involves all the data inside the table, all columns

searchString: What you want to search inside the columns (inside the table).

Hence, you can define which columns to be searched inside the transform function.

In this case, the columns to be searched are builderId, groupName and companyPersonName

Pipe file

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: "arrayFilter"
})

export class BuilderFilterPipe implements PipeTransform {

    transform(value:any[],searchString:string ){

       if(!searchString){
         console.log('no search')
         return value
       }

       return value.filter(it=>{
           const builderId = it.builderId.toString().includes(searchString)
           const groupName = it.groupName.toLowerCase().includes(searchString.toLowerCase())
           const companyPersonName = it.companyPersonName.toLowerCase().includes(searchString.toLowerCase())
           console.log( builderId + groupName + companyPersonName);
           return (builderId + groupName + companyPersonName );
       })
    }
}
</code>```

What does the transform function do?

builderId, groupName and companyPersonName are the three fields I searched

builderId converted to string because our searchString is in string format.

toLowerCase() is used to make search accurate irrespective of user search in lowercase or uppercase

Html:

```<code>  <tr *ngFor = "let builder of newBuilderDetailsArray | arrayFilter:search" >
      <td>{{builder.builderId}}</td>
      <td>{{builder.groupName}}</td>
      <td>{{builder.companyPersonName}}</td>
  </tr>
</code>```

Make sure your filter.ts file added to module.ts file

Body:
Hi everyone.
  I want to make a custom filter for my table which intakes more than one argument
  to search multiple columns .. in my case right now only one argument can be passed .
  thanks in advance

component.html

    <mat-checkbox></mat-checkbox>
    {{builder.builderId}}
    {{builder.viewDateAdded}}
    {{builder.viewLastEdit}}
    {{builder.groupName}}
    {{builder.companyPersonName}}
    <button mat-button color="primary">UPDATE</button>

pipe.ts

@Pipe({
    name: "filter",
    pure:false
})

export class FilterPipe implements PipeTransform {
    transform(items: any[], field: string, value: string): any[] {
    if (!items) {
        return [];
    }
    if (!field || !value) {
        return items;
    }
    return items.filter(singleItem =>
        singleItem[field].toLowerCase().includes(value.toLowerCase()) );
}

Body:
Created multiple arguments pipe in angular 4

The code lets you search through multiple columns in your table.

Passed 2 arguments in the transform function

value: Which involves all the data inside the table, all columns

searchString: What you want to search inside the columns (inside the table).

Hence, you can define which columns to be searched inside the transform function.

In this case, the columns to be searched are builderId, groupName and companyPersonName

Pipe file

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: "arrayFilter"
})

export class BuilderFilterPipe implements PipeTransform {

    transform(value:any[],searchString:string ){

       if(!searchString){
         console.log('no search')
         return value
       }

       return value.filter(it=>{
           const builderId = it.builderId.toString().includes(searchString)
           const groupName = it.groupName.toLowerCase().includes(searchString.toLowerCase())
           const companyPersonName = it.companyPersonName.toLowerCase().includes(searchString.toLowerCase())
           console.log( builderId + groupName + companyPersonName);
           return (builderId + groupName + companyPersonName );
       })
    }
}

What does the transform function do?

builderId, groupName and companyPersonName are the three fields I searched

builderId converted to string because our searchString is in string format.

toLowerCase() is used to make search accurate irrespective of user search in lowercase or uppercase

Html:

  <tr *ngFor = "let builder of newBuilderDetailsArray | arrayFilter:search" >
      <td>{{builder.builderId}}</td>
      <td>{{builder.groupName}}</td>
      <td>{{builder.companyPersonName}}</td>
  </tr>

Make sure your filter.ts file added to module.ts file


问:
display data in view that assign through model
excuse me for my lack of understanding regarding this matter. so let me get to my problem. I create a model that contains an information like this.

```<code>export class Organization {
     orgId?: string;
     orgName: string;
     orgAddress: string;
}
</code>```

and then I import it to my controller with my service to get my data.

```<code>import { Organization } from '../model/organization';
import { OrganizationService } from '../service/organization/organization.service';
</code>```

so having said that. i set my model and services in order to get my data.

```<code> organization: Organization

 ngOnInit() {
   this.orgSvc.getUserOrganization().subscribe(org => {
    this.organization = org.data();
    console.log(this.organization );
 })
}
</code>```

if I console.log the data. it will print out all the data that I need.

```<code>{
    orgId: 'sdfasfasdfcv',
    orgName: 'testOrg',
    orgAddress: 'street test'
 }
</code>```

but everytime that I display it to my view. it get me an error of property of undefined.

```<code>{{ organization.orgName }}
</code>```

what did i miss? I read the documentation of angular io. even if I create a new instance. like this.organizationData = new Organization('', '', '' ... ) it doesn't work.

答:
use typesafe ? operator

```<code>{{ organization?.orgName }}
</code>```

It is because the service call is made after the DOM is rendered. At the time of rendering the object is undefined when you are trying to access its properties it is not available. The above fix will prevent the initial error

More information read here

Body:
excuse me for my lack of understanding regarding this matter. so let me get to my problem. I create a model that contains an information like this.

export class Organization {
     orgId?: string;
     orgName: string;
     orgAddress: string;
}

and then I import it to my controller with my service to get my data.

import { Organization } from '../model/organization';
import { OrganizationService } from '../service/organization/organization.service';

so having said that. i set my model and services in order to get my data.

 organization: Organization

 ngOnInit() {
   this.orgSvc.getUserOrganization().subscribe(org => {
    this.organization = org.data();
    console.log(this.organization );
 })
}

if I console.log the data. it will print out all the data that I need.

{
    orgId: 'sdfasfasdfcv',
    orgName: 'testOrg',
    orgAddress: 'street test'
 }

but everytime that I display it to my view. it get me an error of property of undefined.

{{ organization.orgName }}

what did i miss? I read the documentation of angular io. even if I create a new instance. like this.organizationData = new Organization('', '', '' ... ) it doesn't work.

Body:
use typesafe ? operator

{{ organization?.orgName }}

It is because the service call is made after the DOM is rendered. At the time of rendering the object is undefined when you are trying to access its properties it is not available. The above fix will prevent the initial error

More information read here