问:
Remove emoji or smiley characters in SQL Server ntext column?
I have a mobile chat conversation text area which is stored in ntext data type in SQL Server 2008. I am doing some process character by character. I need to do something I do not know to pass these kind of emoji characters. Should I eliminate them or collate to different collation or encode to different char-set. My table's collation type is Latin1_General_CI_AS. I need something like this:

```<code>IF(SUBSTRING(@chat_Conversation, @i, 1) = 'Emoji')
    CONTINUE;
</code>```

答:
As a first guess I'd suggest to place an N in front of your literal

Compare the results:

```<code>SELECT  ''
      ,N'';
</code>```

The result

```<code>ExtASCII    Unicode
??
</code>```

Without the N the literal is read as extended ASCII, unknown characters are returned as question marks. With N you are dealing with UNICODE (to be exact: UCS-2)...

UPDATE

As pointed out in comments: Do not use NTEXT!

NTEXT, TEXT and IMAGE are deprecated for centuries! These types will not be supported in future versions!

Convert all your work (columns, variables...) to

NTEXT -> NVARCHAR(MAX) (covering UCS-2 characters)

TEXT  -> VARCHAR(MAX)  (covering extended ASCII, depending on COLLATION and code page)

IMAGE -> VARBINARY(MAX) (covering BLOBs)

Hint

If you are dealing with special characters like foreign alphabets or emojis you should always use the N with literals and with types...

Body:
I have a mobile chat conversation text area which is stored in ntext data type in SQL Server 2008. I am doing some process character by character. I need to do something I do not know to pass these kind of emoji characters. Should I eliminate them or collate to different collation or encode to different char-set. My table's collation type is Latin1_General_CI_AS. I need something like this:

IF(SUBSTRING(@chat_Conversation, @i, 1) = 'Emoji')
    CONTINUE;

Body:
As a first guess I'd suggest to place an N in front of your literal

Compare the results:

SELECT  ''
      ,N'';

The result

ExtASCII    Unicode
??

Without the N the literal is read as extended ASCII, unknown characters are returned as question marks. With N you are dealing with UNICODE (to be exact: UCS-2)...

UPDATE

As pointed out in comments: Do not use NTEXT!

NTEXT, TEXT and IMAGE are deprecated for centuries! These types will not be supported in future versions!

Convert all your work (columns, variables...) to

NTEXT -> NVARCHAR(MAX) (covering UCS-2 characters)

TEXT  -> VARCHAR(MAX)  (covering extended ASCII, depending on COLLATION and code page)

IMAGE -> VARBINARY(MAX) (covering BLOBs)

Hint

If you are dealing with special characters like foreign alphabets or emojis you should always use the N with literals and with types...


来源: stackexchange

问:
In react-native TextInput box show a line, how to removed it
MY React-native APP I make a Input box but I get a line in Input box... How can I remove it?

```<code><View style={styles.inputContainer}>
  <TextInput style={styles.input} onChangeText={(text) => this.setState({editTodoVal: text})} value={this.state.editTodoVal}/>
</View>
</code>```

Style:

```<code>inputContainer: {
        marginTop: 5,
        padding: 10,
        flexDirection: 'row'
    },
 input: {
        height: 40,
        padding: 4,
        marginRight: 5,
        flex: 6,
        fontSize: 18,
        borderWidth: 1,
        borderColor: '#fff',
        backgroundColor: '#fff',
        borderRadius: 1,
        color: '#000',
    },
</code>```

Please check my Images for more seance:

答: By default it comes with underline, if you need to remove then use : underlineColorAndroid='transparent' . Also check documentation for more information.

ContentLicense: CC BY-SA 3.0

Body:
MY React-native APP I make a Input box but I get a line in Input box... How can I remove it?

<View style={styles.inputContainer}>
  <TextInput style={styles.input} onChangeText={(text) => this.setState({editTodoVal: text})} value={this.state.editTodoVal}/>
</View>

Style:

inputContainer: {
        marginTop: 5,
        padding: 10,
        flexDirection: 'row'
    },
 input: {
        height: 40,
        padding: 4,
        marginRight: 5,
        flex: 6,
        fontSize: 18,
        borderWidth: 1,
        borderColor: '#fff',
        backgroundColor: '#fff',
        borderRadius: 1,
        color: '#000',
    },

Please check my Images for more seance:


问:
Data Binding Android Recycler view
I am using android data binding and following is the class which I am using to set Variable

```<code>public class DayTemp extends BaseObservable implements Serializable {

    @SerializedName("dt")
    long date;
    @SerializedName("pressure")
    double pressure;
    @SerializedName("humidity")
    long humidity;
    @SerializedName("temp")
    Temp temp;
    @SerializedName("weather")
    ArrayList<Weather> weathers;
    @SerializedName("speed")
    double speed;
    @SerializedName("deg")
    double deg;
    @SerializedName("clouds")
    double clouds;

    @Bindable
    public long getDate() {
        return date;
    }

    public void setDate(long date) {
        this.date = date;
        notifyPropertyChanged(BR.date);
    }

    @Bindable
    public double getPressure() {
        return pressure;
    }

    public void setPressure(double pressure) {
        this.pressure = pressure;
        notifyPropertyChanged(BR.pressure);
    }

    @Bindable
    public long getHumidity() {
        return humidity;
    }

    public void setHumidity(long humidity) {
        this.humidity = humidity;
        notifyPropertyChanged(BR.humidity);
    }

    @Bindable
    public Temp getTemp() {
        return temp;
    }

    public void setTemp(Temp temp) {
        this.temp = temp;
        notifyPropertyChanged(BR.temp);
    }

    @Bindable
    public ArrayList<Weather> getWeathers() {
        return weathers;
    }

    public void setWeathers(ArrayList<Weather> weathers) {
        this.weathers = weathers;
        notifyPropertyChanged(BR.weathers);
    }

    @Bindable
    public double getSpeed() {
        return speed;
    }

    public void setSpeed(double speed) {
        this.speed = speed;
        notifyPropertyChanged(BR.speed);
    }

    @Bindable
    public double getDeg() {
        return deg;
    }

    public void setDeg(double deg) {
        this.deg = deg;
        notifyPropertyChanged(BR.deg);
    }

    @Bindable
    public double getClouds() {
        return clouds;
    }

    public void setClouds(double clouds) {
        this.clouds = clouds;
        notifyPropertyChanged(BR.clouds);
    }
}
</code>```

As In this POJO class I am able to set all the values to my recyclerview bt I can't access the weathers arraylist and also not able to get the fields related to it.

```<code>public class Weather extends BaseObservable implements Serializable {

    @SerializedName("id")
    long id;
    @SerializedName("main")
    String main;
    @SerializedName("description")
    String desc;
    @SerializedName("icon")
    String icon;

    @Bindable
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
        notifyPropertyChanged(BR.id);
    }

    @Bindable
    public String getMain() {
        return main;
    }

    public void setMain(String main) {
        this.main = main;
        notifyPropertyChanged(BR.main);
    }

    @Bindable
    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
        notifyPropertyChanged(BR.desc);
    }

    @Bindable
    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
        notifyPropertyChanged(BR.icon);
    }
}
</code>```

Layout file:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
  >

    <data>

        <import  type="com.weatherappforleftshift.currentlocation.DateUtils"/>

        <variable
            name="daytemp" type="com.weatherappforleftshift.currentlocation.model.DayTemp"/>

    </data>

           <TextView
                    android:id="@+id/weather_status"
                    android:layout_width="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_marginStart="10dp"
                    android:text="@{HOW TO SET TEXT HERE FROM weathers list}"
                    android:layout_height="wrap_content" />

</layout>
</code>```

I want to set Icon and Description from weather class to my recyclerview.

How to achieve this in the item layout????

答:
You can look at this github project

https://github.com/arunshankar87/triptrial

I have handled the data binding for a recyclerview

More specifically the below 2 files will be of interest

https://github.com/arunshankar87/triptrial/blob/master/app/src/main/java/com/arunshankar/triptrial/MyAdapter.java

https://github.com/arunshankar87/triptrial/blob/master/app/src/main/res/layout/row_layout.xml

Title: Data Binding Android Recycler view

Body:
I am using android data binding and following is the class which I am using to set Variable

public class DayTemp extends BaseObservable implements Serializable {

    @SerializedName("dt")
    long date;
    @SerializedName("pressure")
    double pressure;
    @SerializedName("humidity")
    long humidity;
    @SerializedName("temp")
    Temp temp;
    @SerializedName("weather")
    ArrayList<Weather> weathers;
    @SerializedName("speed")
    double speed;
    @SerializedName("deg")
    double deg;
    @SerializedName("clouds")
    double clouds;

    @Bindable
    public long getDate() {
        return date;
    }

    public void setDate(long date) {
        this.date = date;
        notifyPropertyChanged(BR.date);
    }

    @Bindable
    public double getPressure() {
        return pressure;
    }

    public void setPressure(double pressure) {
        this.pressure = pressure;
        notifyPropertyChanged(BR.pressure);
    }

    @Bindable
    public long getHumidity() {
        return humidity;
    }

    public void setHumidity(long humidity) {
        this.humidity = humidity;
        notifyPropertyChanged(BR.humidity);
    }

    @Bindable
    public Temp getTemp() {
        return temp;
    }

    public void setTemp(Temp temp) {
        this.temp = temp;
        notifyPropertyChanged(BR.temp);
    }

    @Bindable
    public ArrayList<Weather> getWeathers() {
        return weathers;
    }

    public void setWeathers(ArrayList<Weather> weathers) {
        this.weathers = weathers;
        notifyPropertyChanged(BR.weathers);
    }

    @Bindable
    public double getSpeed() {
        return speed;
    }

    public void setSpeed(double speed) {
        this.speed = speed;
        notifyPropertyChanged(BR.speed);
    }

    @Bindable
    public double getDeg() {
        return deg;
    }

    public void setDeg(double deg) {
        this.deg = deg;
        notifyPropertyChanged(BR.deg);
    }

    @Bindable
    public double getClouds() {
        return clouds;
    }

    public void setClouds(double clouds) {
        this.clouds = clouds;
        notifyPropertyChanged(BR.clouds);
    }
}

As In this POJO class I am able to set all the values to my recyclerview bt I can't access the weathers arraylist and also not able to get the fields related to it.

public class Weather extends BaseObservable implements Serializable {

    @SerializedName("id")
    long id;
    @SerializedName("main")
    String main;
    @SerializedName("description")
    String desc;
    @SerializedName("icon")
    String icon;

    @Bindable
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
        notifyPropertyChanged(BR.id);
    }

    @Bindable
    public String getMain() {
        return main;
    }

    public void setMain(String main) {
        this.main = main;
        notifyPropertyChanged(BR.main);
    }

    @Bindable
    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
        notifyPropertyChanged(BR.desc);
    }

    @Bindable
    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
        notifyPropertyChanged(BR.icon);
    }
}

Layout file:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
  >

    <data>

        <import  type="com.weatherappforleftshift.currentlocation.DateUtils"/>

        <variable
            name="daytemp" type="com.weatherappforleftshift.currentlocation.model.DayTemp"/>

    </data>

           <TextView
                    android:id="@+id/weather_status"
                    android:layout_width="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_marginStart="10dp"
                    android:text="@{HOW TO SET TEXT HERE FROM weathers list}"
                    android:layout_height="wrap_content" />

</layout>

I want to set Icon and Description from weather class to my recyclerview.

How to achieve this in the item layout????


问:
Function with variable parameter type
I have these two functions which are basically the same:

```<code>private Order getOrder( List<Order> orders, String gcsId )
{
    Predicate<Order> predicate = c -> c.getGcsId().equals( gcsId );
    Order obj = orders.stream().filter( predicate ).findFirst().get();
    return obj;
}

private OrderLine getOrderLine( List<OrderLine> orderLines, String gcsId )
{
    Predicate<OrderLine> predicate = c -> c.getGcsId().equals( gcsId );
    OrderLine obj = orderLines.stream().filter( predicate ).findFirst().get();
    return obj;
}
</code>```

The only difference is the type of the first parameter. How can I create a single function with the first parameter having a variable type?

Edit: This is how I call those functions in another method of the same class:

```<code>Order order = getOrder( orders, orderId );
OrderLine orderLine = getOrderLine( order.getOrderLines(), orderLineId );
</code>```

答:
Either make them implement a common interface, which defined the getGcsId() method, and use

```<code>private <T extends CommonInterface> T getFirstWithGcsId(List<T> orders, String gcsId) {
    Predicate<T> predicate = c -> c.getGcsId().equals(gcsId);
    T obj = orders.stream().filter(predicate).findFirst().get();
    return obj;
}
</code>```

Or change the signature of the method to pass it a function which knows how to extract the gcsId:

```<code>private <T> T getFirstWithGcsId(List<T> orders, String gcsId, Function<T, String> gcsIdExtractor) {
    Predicate<T> predicate = c -> gcsIdExtractor.apply(c).equals(gcsId);
    T obj = orders.stream().filter(predicate).findFirst().get();
    return obj;
}
</code>```

But this method is so simple that, frankly, if you don't have any common interface, I would just inline it. It's basically one line of code:

```<code>Order firstOrder = orders.stream().filter(o -> o.getGcsId().equals(gcsId)).findFirst().get();
</code>```

You should also avoid calling get() on an Optional in general. Rather prefer something like

```<code>Order firstOrder = orders.stream().filter(o -> o.getGcsId().equals(gcsId)).findFirst().orElseThrow(() -> new IllegalStateException("no first order with gcsId " + gcsId));
</code>```

Title: Function with variable parameter type

Body:
I have these two functions which are basically the same:

private Order getOrder( List<Order> orders, String gcsId )
{
    Predicate<Order> predicate = c -> c.getGcsId().equals( gcsId );
    Order obj = orders.stream().filter( predicate ).findFirst().get();
    return obj;
}

private OrderLine getOrderLine( List<OrderLine> orderLines, String gcsId )
{
    Predicate<OrderLine> predicate = c -> c.getGcsId().equals( gcsId );
    OrderLine obj = orderLines.stream().filter( predicate ).findFirst().get();
    return obj;
}

The only difference is the type of the first parameter. How can I create a single function with the first parameter having a variable type?

Edit: This is how I call those functions in another method of the same class:

Order order = getOrder( orders, orderId );
OrderLine orderLine = getOrderLine( order.getOrderLines(), orderLineId );

Body:
Either make them implement a common interface, which defined the getGcsId() method, and use

private <T extends CommonInterface> T getFirstWithGcsId(List<T> orders, String gcsId) {
    Predicate<T> predicate = c -> c.getGcsId().equals(gcsId);
    T obj = orders.stream().filter(predicate).findFirst().get();
    return obj;
}

Or change the signature of the method to pass it a function which knows how to extract the gcsId:

private <T> T getFirstWithGcsId(List<T> orders, String gcsId, Function<T, String> gcsIdExtractor) {
    Predicate<T> predicate = c -> gcsIdExtractor.apply(c).equals(gcsId);
    T obj = orders.stream().filter(predicate).findFirst().get();
    return obj;
}

But this method is so simple that, frankly, if you don't have any common interface, I would just inline it. It's basically one line of code:

Order firstOrder = orders.stream().filter(o -> o.getGcsId().equals(gcsId)).findFirst().get();

You should also avoid calling get() on an Optional in general. Rather prefer something like

Order firstOrder = orders.stream().filter(o -> o.getGcsId().equals(gcsId)).findFirst().orElseThrow(() -> new IllegalStateException("no first order with gcsId " + gcsId));


问:
I am using .NET Core with C# on Linux, and library *System.Drawing* is missing

Error message

Program.cs(1,14): error CS0234: The type or namespace name 'Drawing'
does not exist in the namespace 'System' (are you missing an assembly
reference?

Is it possible to fix that? Or I am not meant to be using this library, if I am developing on Linux with C#?

答:
2021:

Quote from System.Drawing.Common only supported on Windows, Recommended action:

To use these APIs for cross-platform apps, migrate to one of the following libraries:

ImageSharp

SkiaSharp

Microsoft.Maui.Graphics

You are able to use System.Drawing for the short term but be aware there is no support.

Alternatively, you can enable support for non-Windows platforms by setting the System.Drawing.EnableUnixSupport runtime configuration switch to true in the runtimeconfig.json file:

This configuration switch was added to give cross-platform apps that depend heavily on this package time to migrate to more modern libraries. However, non-Windows bugs will not be fixed. In addition, we may completely remove support for non-Windows platforms in a future release, even if you enable it using the runtime configuration switch.

To be able to use System.Drawing on Linux machines, you might also need to install libgdiplus as mentioned by @saman-azadi and @alex-from-jitbit.

2017:

The System.Drawing namespace is at the moment not part of corefx as it relies on the GDI+ features from Windows.

But there are plans to support it in the future.

But there are multiple alternatives:

CoreCompat.System.Drawing

CoreCompat.System.Drawing is a .NET Core port of the Mono implementation of System.Drawing. Like System.Drawing in .NET Framework and in Mono, CoreCompat.System.Drawing also relies on GDI+ on Windows. Caution is therefore advised, for the same reasons.

ImageSharp

ImageSharp is a brand new, pure managed code, and cross-platform image processing library. Its performance is not as good as that of libraries relying on native OS-specific dependencies, but it remains very reasonable. Its only dependency is .NET itself, which makes it extremely portable: there is no additional package to install, just reference ImageSharp itself, and you’re done.

Magick.NET

Magick.NET is the .NET wrapper for the popular ImageMagick library. ImageMagick is an open-source, cross-platform library that focuses on image quality, and on offering a very wide choice of supported image formats. It also has the same support for EXIF as ImageSharp.

(The .NET Core build of Magick.NET currently only supports Windows.)

SkiaSharp

SkiaSharp is the .NET wrapper for Google’s Skia cross-platform 2D graphics library, that is maintained by the Xamarin team. SkiaSharp is now compatible with .NET Core, and is extremely fast.

FreeImage-dotnet-core

This library is to the native FreeImage library what Magick.NET is to ImageMagick: a .NET Core wrapper. It offers a nice choice of image formats, good performance, and good visual quality.

Here are some good examples and performance analyses of the libraries mentioned above.

ContentLicense: CC BY-SA 4.0


问:
Lock two timers on different object
I have several objects which require same function to be executed at different time. Some objects of them are mutual exclusive, some are not.

So to be short, I illustrate this short example with only two timers

Do these two timers work on parallel? Or should I use a different approach?

```<code>class MyTimer:Timer
{
   private static int count=0;
   public int Id {get; private set;}
   public MyTimer(){ Id= count++;}
}

...
object[] lockers = new object[2]{new object(), new object()};
MyTimer[] timers = new MyTimer[2]{ new MyTimer(), new MyTimer()};
...
/* somewhere */
timers[0].Elapsed += Time_Elapsed;
timers[1].Elapsed += Time_Elapsed;
timers[0].Start();
timers[1].Start();
...
private void Time_Elapsed(object sender, ElapsedEventArgs e)
{
    MyTimer timer = sender as MyTimer;
    lock(lockers[timer.Id])
    {
        /* part of code depends on timer.Id*/
    }
}
</code>```

EDIT AFTER  Kennyzx answer (I did not want to write too much code but I was not clear above about what I wanted ask):

```<code>interface IWorker
  {
   void DoSomething();
  }
class MyTimer:Timer
{
   public int Id {get; private set;}
   public IWorker Worker;
   public MyTimer(int id){ Id=id;}
}
...
object[] lockers = new object[2]{new object(), new object()};
MyTimer[] timers = new MyTimer[3]{ new MyTimer(0), new MyTimer(1),new MyTimer(1)};
...
/* somewhere */
timers[0].Elapsed += Time_Elapsed;
timers[1].Elapsed += Time_Elapsed;
timers[2].Elapsed += Time_Elapsed;

timers[0].Worker = Worker_A; // implement IWorker
timers[1].Worker = Worker_B; // implement IWorker
timers[2].Worker = Worker_C; // implement IWorker
timers[0].Start();    timers[1].Start();    timers[2].Start();
...
private void Time_Elapsed(object sender, ElapsedEventArgs e)
{
    MyTimer timer = sender as MyTimer;
    lock(lockers[timer.Id])
    {
        timer.Worker.DoSomething();
    }
}
</code>```

In this new example Worker_B and Worker_C are mutually exlusive (because timer.Id is the same). But Worker_A can work in parallel with them.
Is it correct way to achieve it?

答:
Do these two timers work on parallel？

For System.Timers.Timer, the Elapsed event is raised on a ThreadPool thread, which mean the event handlers can run on parellel.

But your lock statement is somehow problematic, how can you guarantee mutual exclusive? Should lock on the same instance of object.

```<code>object locker = new object();

...

private void Time_Elapsed(object sender, ElapsedEventArgs e)
{
    lock(locker)
    {
        ...
</code>```

Title: Lock two timers on different object

Body:
I have several objects which require same function to be executed at different time. Some objects of them are mutual exclusive, some are not.

So to be short, I illustrate this short example with only two timers

Do these two timers work on parallel? Or should I use a different approach?

class MyTimer:Timer
{
   private static int count=0;
   public int Id {get; private set;}
   public MyTimer(){ Id= count++;}
}

...
object[] lockers = new object[2]{new object(), new object()};
MyTimer[] timers = new MyTimer[2]{ new MyTimer(), new MyTimer()};
...
/* somewhere */
timers[0].Elapsed += Time_Elapsed;
timers[1].Elapsed += Time_Elapsed;
timers[0].Start();
timers[1].Start();
...
private void Time_Elapsed(object sender, ElapsedEventArgs e)
{
    MyTimer timer = sender as MyTimer;
    lock(lockers[timer.Id])
    {
        /* part of code depends on timer.Id*/
    }
}

EDIT AFTER  Kennyzx answer (I did not want to write too much code but I was not clear above about what I wanted ask):

interface IWorker
  {
   void DoSomething();
  }
class MyTimer:Timer
{
   public int Id {get; private set;}
   public IWorker Worker;
   public MyTimer(int id){ Id=id;}
}
...
object[] lockers = new object[2]{new object(), new object()};
MyTimer[] timers = new MyTimer[3]{ new MyTimer(0), new MyTimer(1),new MyTimer(1)};
...
/* somewhere */
timers[0].Elapsed += Time_Elapsed;
timers[1].Elapsed += Time_Elapsed;
timers[2].Elapsed += Time_Elapsed;

timers[0].Worker = Worker_A; // implement IWorker
timers[1].Worker = Worker_B; // implement IWorker
timers[2].Worker = Worker_C; // implement IWorker
timers[0].Start();    timers[1].Start();    timers[2].Start();
...
private void Time_Elapsed(object sender, ElapsedEventArgs e)
{
    MyTimer timer = sender as MyTimer;
    lock(lockers[timer.Id])
    {
        timer.Worker.DoSomething();
    }
}

In this new example Worker_B and Worker_C are mutually exlusive (because timer.Id is the same). But Worker_A can work in parallel with them.
Is it correct way to achieve it?

Body:
Do these two timers work on parallel？

For System.Timers.Timer, the Elapsed event is raised on a ThreadPool thread, which mean the event handlers can run on parellel.

But your lock statement is somehow problematic, how can you guarantee mutual exclusive? Should lock on the same instance of object.

object locker = new object();

...

private void Time_Elapsed(object sender, ElapsedEventArgs e)
{
    lock(locker)
    {
        ...


问:
(AngularJS) Most efficient way to replace values in array globally
I want to replace all values in my array, here's the code:

```<code>var jsonImg = [
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 01.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 02.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 03.jpg"}
];

var imgUrl = JSON.stringify(jsonImg);
var oldString = imgUrl;
var newString = oldString.replace(/https:\/\/example.amazonaws.com\/images-lib\//g,"cordova.url/");

$scope.Images = JSON.parse(newString);
</code>```

But I think JSON.Stringfly and JSON.Parse are a bit redundant here, Do you think this is the most efficient way to replace all of the value JSON.Stringfly and JSON.Parse? are there some other alternative to do this? Please check the fiddle here:
https://jsfiddle.net/dedenbangkit/zu7utr6a/3/

答:
You are right. There is no need to convert to string and back. Though when it comes to small number of values in array, it wouldn't matter much in terms of efficiency. But, why convert to string and back when you can have such powerful functions for array itself.

Something like:

```<code>$scope.Images = jsonImg.map(function(obj) {
  obj.url = "cordova.url" + obj.url.substr(obj.url.lastIndexOf("/"))
  return obj;
});
</code>```

updated fiddle

Body:
I want to replace all values in my array, here's the code:

var jsonImg = [
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 01.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 02.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 03.jpg"}
];

var imgUrl = JSON.stringify(jsonImg);
var oldString = imgUrl;
var newString = oldString.replace(/https:\/\/example.amazonaws.com\/images-lib\//g,"cordova.url/");

$scope.Images = JSON.parse(newString);

But I think JSON.Stringfly and JSON.Parse are a bit redundant here, Do you think this is the most efficient way to replace all of the value JSON.Stringfly and JSON.Parse? are there some other alternative to do this? Please check the fiddle here:
https://jsfiddle.net/dedenbangkit/zu7utr6a/3/

Body:
You are right. There is no need to convert to string and back. Though when it comes to small number of values in array, it wouldn't matter much in terms of efficiency. But, why convert to string and back when you can have such powerful functions for array itself.

Something like:

$scope.Images = jsonImg.map(function(obj) {
  obj.url = "cordova.url" + obj.url.substr(obj.url.lastIndexOf("/"))
  return obj;
});

updated fiddle


问:
using MVC Model Binder, how to prevent binding inner complex object properties?
i have the following model

```<code>public class Person
{
    public int Id {get;set;}
    [Required()]
    public string Name {get;set;}
    [Required()]
    public Address Address {get;set;}
}

public class Address
{
    public int Id {get;set;}
    [Required()]
    public string City {get;set;}
    [Required()]
    public string Street {get;set;}
}
</code>```

in the controller:

```<code> [HttpPost]
        public ActionResult Create(Person entity)
        {
            if (ViewData.ModelState.IsValid)
            {
                ///Some code
                return this.RedirectToAction("Browse");
            }
            else
            {
                return View("Edit", ViewModel);
            }
        }
</code>```

the problem is that the binder try to validate even the inner address class, but all i care for, is the AddressID
but the ModelBinder insist to validate even the City and Street properties.

how can i simply override the original ModelBinder just to validate the ID of the inner object (which is in my situation is AddressID)??

is there a simple way ?

答:
It sounds like your entity and your model have two different requirements.  If that is the case, then they should be two different classes.  Write a separate Person and address class for MVC to bind to and don't have city or street be required.

Another possible, but less elegant solution, is to not rely on MVC doing the model binding.  If you only have a handful of values that may be acceptable, but if you have a lot, then I would use my first suggestion.

Body:
i have the following model

public class Person
{
    public int Id {get;set;}
    [Required()]
    public string Name {get;set;}
    [Required()]
    public Address Address {get;set;}
}

public class Address
{
    public int Id {get;set;}
    [Required()]
    public string City {get;set;}
    [Required()]
    public string Street {get;set;}
}

in the controller:

 [HttpPost]
        public ActionResult Create(Person entity)
        {
            if (ViewData.ModelState.IsValid)
            {
                ///Some code
                return this.RedirectToAction("Browse");
            }
            else
            {
                return View("Edit", ViewModel);
            }
        }

the problem is that the binder try to validate even the inner address class, but all i care for, is the AddressID
but the ModelBinder insist to validate even the City and Street properties.

how can i simply override the original ModelBinder just to validate the ID of the inner object (which is in my situation is AddressID)??

is there a simple way ?

ContentLicense: CC BY-SA 2.5


问:
Using Azure SQL Services from a Mac?
Azure SQL Services looks pretty cool, and I'd like to use it as a hosted database. I set myself up with a starter web edition database, and after clicking through a million and five EULAs, I got to a console and created a database. It gave me a connection string for ODBC, and for ADO.NET.

I'm using a Mac, with 10.6. What are my options?

Ideally, I'd find something like Sequel Pro or Querious that works with ODBC. Failing that, is there a web console or something?

I suppose there's always DBI::Shell in perl.

Is there anything better than installing Windows 7/VS2010 in VMWare?

答: Use Visual Studio Code with mssql extension to connect and query data on Azure SQL database.</p>

Title: Using Azure SQL Services from a Mac?


问:
Why some methods are not either private or public?
I have seen some examples that don't declare methods to be private or public. Just static like: static Bitmap resamplePic(Context context, String imagePath)

Why is that? And when to do that?
This is my example code:

```<code>/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.emojify;

import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.support.v4.content.FileProvider; import android.util.DisplayMetrics; import android.view.WindowManager; import android.widget.Toast;

import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;

class BitmapUtils {

    private static final String FILE_PROVIDER_AUTHORITY = "com.example.android.fileprovider";

    /**
     * Resamples the captured photo to fit the screen for better memory usage.
     *
     * @param context   The application context.
     * @param imagePath The path of the photo to be resampled.
     * @return The resampled bitmap
     */
    static Bitmap resamplePic(Context context, String imagePath) {

        // Get device screen size information
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(metrics);

        int targetH = metrics.heightPixels;
        int targetW = metrics.widthPixels;

        // Get the dimensions of the original bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;

        return BitmapFactory.decodeFile(imagePath);
    }

    /**
     * Creates the temporary image file in the cache directory.
     *
     * @return The temporary image file.
     * @throws IOException Thrown if there is an error creating the file
     */
    static File createTempImageFile(Context context) throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = context.getExternalCacheDir();

        return File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
    }

    /**
     * Deletes image file for a given path.
     *
     * @param context   The application context.
     * @param imagePath The path of the photo to be deleted.
     */
    static boolean deleteImageFile(Context context, String imagePath) {
        // Get the file
        File imageFile = new File(imagePath);

        // Delete the image
        boolean deleted = imageFile.delete();

        // If there is an error deleting the file, show a Toast
        if (!deleted) {
            String errorMessage = context.getString(R.string.error);
            Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
        }

        return deleted;
    }

    /**
     * Helper method for adding the photo to the system photo gallery so it can be accessed
     * from other apps.
     *
     * @param imagePath The path of the saved image
     */
    private static void galleryAddPic(Context context, String imagePath) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(imagePath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }

    /**
     * Helper method for saving the image.
     *
     * @param context The application context.
     * @param image   The image to be saved.
     * @return The path of the saved image.
     */
    static String saveImage(Context context, Bitmap image) {

        String savedImagePath = null;

        // Create the new file in the external storage
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + ".jpg";
        File storageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                        + "/Emojify");
        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdirs();
        }

        // Save the new Bitmap
        if (success) {
            File imageFile = new File(storageDir, imageFileName);
            savedImagePath = imageFile.getAbsolutePath();
            try {
                OutputStream fOut = new FileOutputStream(imageFile);
                image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                fOut.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Add the image to the system gallery
            galleryAddPic(context, savedImagePath);

            // Show a Toast with the save location
            String savedMessage = context.getString(R.string.saved_message, savedImagePath);
            Toast.makeText(context, savedMessage, Toast.LENGTH_SHORT).show();
        }

        return savedImagePath;
    }

    /**
     * Helper method for sharing an image.
     *
     * @param context   The image context.
     * @param imagePath The path of the image to be shared.
     */
    static void shareImage(Context context, String imagePath) {
        // Create the share intent and start the share activity
        File imageFile = new File(imagePath);
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        Uri photoURI = FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, imageFile);
        shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
        context.startActivity(shareIntent);
    } }
</code>```

答:
If a class has no modifier (the default, also known as
  package-private), it is visible only within its own package (packages
  are named groups of related classes)

Body:
I have seen some examples that don't declare methods to be private or public. Just static like: static Bitmap resamplePic(Context context, String imagePath)

Why is that? And when to do that?
This is my example code:

/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.emojify;

import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.support.v4.content.FileProvider; import android.util.DisplayMetrics; import android.view.WindowManager; import android.widget.Toast;

import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;

class BitmapUtils {

    private static final String FILE_PROVIDER_AUTHORITY = "com.example.android.fileprovider";

    /**
     * Resamples the captured photo to fit the screen for better memory usage.
     *
     * @param context   The application context.
     * @param imagePath The path of the photo to be resampled.
     * @return The resampled bitmap
     */
    static Bitmap resamplePic(Context context, String imagePath) {

        // Get device screen size information
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(metrics);

        int targetH = metrics.heightPixels;
        int targetW = metrics.widthPixels;

        // Get the dimensions of the original bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;

        return BitmapFactory.decodeFile(imagePath);
    }

    /**
     * Creates the temporary image file in the cache directory.
     *
     * @return The temporary image file.
     * @throws IOException Thrown if there is an error creating the file
     */
    static File createTempImageFile(Context context) throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = context.getExternalCacheDir();

        return File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
    }

    /**
     * Deletes image file for a given path.
     *
     * @param context   The application context.
     * @param imagePath The path of the photo to be deleted.
     */
    static boolean deleteImageFile(Context context, String imagePath) {
        // Get the file
        File imageFile = new File(imagePath);

        // Delete the image
        boolean deleted = imageFile.delete();

        // If there is an error deleting the file, show a Toast
        if (!deleted) {
            String errorMessage = context.getString(R.string.error);
            Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
        }

        return deleted;
    }

    /**
     * Helper method for adding the photo to the system photo gallery so it can be accessed
     * from other apps.
     *
     * @param imagePath The path of the saved image
     */
    private static void galleryAddPic(Context context, String imagePath) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(imagePath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        context.sendBroadcast(mediaScanIntent);
    }

    /**
     * Helper method for saving the image.
     *
     * @param context The application context.
     * @param image   The image to be saved.
     * @return The path of the saved image.
     */
    static String saveImage(Context context, Bitmap image) {

        String savedImagePath = null;

        // Create the new file in the external storage
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + ".jpg";
        File storageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                        + "/Emojify");
        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdirs();
        }

        // Save the new Bitmap
        if (success) {
            File imageFile = new File(storageDir, imageFileName);
            savedImagePath = imageFile.getAbsolutePath();
            try {
                OutputStream fOut = new FileOutputStream(imageFile);
                image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                fOut.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Add the image to the system gallery
            galleryAddPic(context, savedImagePath);

            // Show a Toast with the save location
            String savedMessage = context.getString(R.string.saved_message, savedImagePath);
            Toast.makeText(context, savedMessage, Toast.LENGTH_SHORT).show();
        }

        return savedImagePath;
    }

    /**
     * Helper method for sharing an image.
     *
     * @param context   The image context.
     * @param imagePath The path of the image to be shared.
     */
    static void shareImage(Context context, String imagePath) {
        // Create the share intent and start the share activity
        File imageFile = new File(imagePath);
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        Uri photoURI = FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, imageFile);
        shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
        context.startActivity(shareIntent);
    } }


问:
I am not able to figure out a bug that is when I try to click on a link on my website it appears the 404
My website is coded in PHP and hosted in Hostinger. The problem is that when I want to go to another link, for example the contact section or the about section it appears the 404 Not Found Page. However, I have tried the same files on local server and it works fine. Would the problem be with the code or with the host provider.

link of my website: http://tranvio.com

.htaccess:

```<code>RewriteEngine on
RewriteBase /public_html
RewriteRule ^details-(.*)?$ index.php?a=details&id=$1 [L]
RewriteRule ^recovery-(.*)?$ index.php?a=recovery&hash=$1 [L]
RewriteRule ^refid=(.*)?$ index.php?refid=$1 [L]
</code>```

答:
```<code>RewriteEngine On
RewriteRule ^testimonials?$ TESTIMONIAL_FILE_PATH_HERE [L]
</code>```

put your .htaccess file in your root directory folder if it's not there.

Body:
My website is coded in PHP and hosted in Hostinger. The problem is that when I want to go to another link, for example the contact section or the about section it appears the 404 Not Found Page. However, I have tried the same files on local server and it works fine. Would the problem be with the code or with the host provider.

link of my website: http://tranvio.com

.htaccess:

RewriteEngine on
RewriteBase /public_html
RewriteRule ^details-(.*)?$ index.php?a=details&id=$1 [L]
RewriteRule ^recovery-(.*)?$ index.php?a=recovery&hash=$1 [L]
RewriteRule ^refid=(.*)?$ index.php?refid=$1 [L]

Body:
RewriteEngine On
RewriteRule ^testimonials?$ TESTIMONIAL_FILE_PATH_HERE [L]

put your .htaccess file in your root directory folder if it's not there.


问:
The sum seems to be 40 but how
I am trying to explore php and to learn it a little bit but when i tried this

```<code>    $n=2;
    $a=5;
    $x=3;
    $s=0;
    $i;
    for($i=1; $i<=($n+2);$i++)
    $s=$s+(2*$i+$a);

   //$g=3*$x+4*$s;
   echo "$s";
</code>```

the result seems to be 40, and when i calculate it by myself the sum of s is 13
I know this is simple but I cannot figure it out.

答: This is simple math. s is the sum of for i from 1 to n+2 of 2i+a. This is equal to the twice sum of i plus the sum of a. The latter is clearly worth (n+2)a. The former is twice the sum of integers from 1 to n+2, i.e. 2 * (n+2)(n+3)/2. The total is thus (n+2)(n+3) + (n+2)a = (n+2)(n+3+a) = (2+2)*(2+3+5) = 4*10 = 40. (Side effect: no need to have an explicit loop, just implement the above formula.)</p>

Title: The sum seems to be 40 but how

Body:
I am trying to explore php and to learn it a little bit but when i tried this

    $n=2;
    $a=5;
    $x=3;
    $s=0;
    $i;
    for($i=1; $i<=($n+2);$i++)
    $s=$s+(2*$i+$a);

   //$g=3*$x+4*$s;
   echo "$s";

the result seems to be 40, and when i calculate it by myself the sum of s is 13
I know this is simple but I cannot figure it out.


问:
SSL Invalidated by Javascript
I have a webpage that requires SSL, but this one line of Javascript appears to invalidate the SSL encryption. Is there any way to stop this line from executing if the page requires SSL?

```<code>var api_url ="http://books.google.com/books?...";
</code>```

That line is the problem....Google Books does not allow SSL connections.

答:
The line you've quoted only assigns a value to a variable - it doesn't actually make a request. ASSUMING you've closed the string in your real code:

```<code>var api_url="http://books.google.com/books";
</code>```

then it won't generate an error. Also, if you're making an AJAX request to Books, you specify the complete URL (including the protocol [http|https]), so the fact that the page that's hosting the JavaScript was retrieved via SSL shouldn't make a difference.

Post some of the surrounding code so we can see what's happening.

Title: SSL Invalidated by Javascript

Body:
I have a webpage that requires SSL, but this one line of Javascript appears to invalidate the SSL encryption. Is there any way to stop this line from executing if the page requires SSL?

var api_url ="http://books.google.com/books?...";

That line is the problem....Google Books does not allow SSL connections.

Body:
The line you've quoted only assigns a value to a variable - it doesn't actually make a request. ASSUMING you've closed the string in your real code:

var api_url="http://books.google.com/books";

then it won't generate an error. Also, if you're making an AJAX request to Books, you specify the complete URL (including the protocol [http|https]), so the fact that the page that's hosting the JavaScript was retrieved via SSL shouldn't make a difference.

Post some of the surrounding code so we can see what's happening.


问:
How to open and close the same div in JQuery
Hey guys how can I close a div which is opend with show().
For Example:
I have a "div a" which includes a "div b" which is hidden at first and when I click on "div a" the "div b" (children) should show up. When I click on an [x] inside the "div b" exactly this div should close.

In my minimal example of this I already find out how to open the right div which is the children of the parent div. But how can I close the parent again? In my example I only can close the "hide Button" but not the whole div "Tag-Cloud". I also tried to implement the parent() function and the parentUntil() function but it failed.

Can you guys help me?

$(document).ready(function() {

  $(".film").click(function() {
    $(this).children(".tag-cloud").show(function() {
      $(".fa-close").click(function() {
        $(this).parent().hide();
      });
    });
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tag-cloud {
  display: none;
}</code>```

Open the div here

tag1

tag2

      [Close Button]

```

答:
3 things to mention

use on('click'.. function it will make your life easyer

both clicks are just clicks so no reason to put one inside the other

event.stopPropagation() is the most important thing here. Cause if you click inside the div to close it you also click on the div itself. with stop propagation you stop the event from bubbeling up the DOM because if not you hide() and then you show() again.

More about event.stopPropagation() can be found here

$(document).ready(function(){

  $(".film").on('click', function (){
    $(this).children(".tag-cloud").show();
  });

  $(".fa-close").on('click', function (event){
    event.stopPropagation();  // do not forget this
    $(this).closest(".tag-cloud").hide();
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tag-cloud {
 display: none;
}</code>```

Open the div here

tag1

tag2

      [Close Button]

```

Body:
Hey guys how can I close a div which is opend with show().
For Example:
I have a "div a" which includes a "div b" which is hidden at first and when I click on "div a" the "div b" (children) should show up. When I click on an [x] inside the "div b" exactly this div should close.

In my minimal example of this I already find out how to open the right div which is the children of the parent div. But how can I close the parent again? In my example I only can close the "hide Button" but not the whole div "Tag-Cloud". I also tried to implement the parent() function and the parentUntil() function but it failed.

Can you guys help me?

$(document).ready(function() {

  $(".film").click(function() {
    $(this).children(".tag-cloud").show(function() {
      $(".fa-close").click(function() {
        $(this).parent().hide();
      });
    });
  });

});

.tag-cloud {
  display: none;
}

Open the div here

tag1

tag2

      [Close Button]

Body:
3 things to mention

use on('click'.. function it will make your life easyer

both clicks are just clicks so no reason to put one inside the other

event.stopPropagation() is the most important thing here. Cause if you click inside the div to close it you also click on the div itself. with stop propagation you stop the event from bubbeling up the DOM because if not you hide() and then you show() again.

More about event.stopPropagation() can be found here

$(document).ready(function(){

  $(".film").on('click', function (){
    $(this).children(".tag-cloud").show();
  });

  $(".fa-close").on('click', function (event){
    event.stopPropagation();  // do not forget this
    $(this).closest(".tag-cloud").hide();
  });

});

.tag-cloud {
 display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="film">

  <h4 class="film-title">Open the div here</h4>

  <div class="tag-cloud"><!-- tag-cloud -->
    <i class="fa fa-2x fa-close"></i>
    <ul>
      <li><a href="">tag1</a></li>
      <li><a href="">tag2</a></li>
    </ul>
    <div class="exit-tags">
      <i class="fa fa-2x fa-close">[Close Button]</i><!-- The close button for the tag-cloud -->
    </div>
  </div>

</div>


问:
Is there a driver for SQLite in Java?
I did some research on their site, and after some Google-ing, it looks like there are only drivers for C & C++. Is there an open driver that I can use with SQLLite, or is there a way I can use it with JDBC?

UPDATE

I'm doing development on Linux, but I would like to keep my options open. Native libraries would work, but wouldn't give the cross-platform freedom that I'm used to with Java.

答: SQLite JDBC is completely written in Java, so there are no external dependencies.</p>

Title: Is there a driver for SQLite in Java?


问:
Python flask rest api
i like to add a rest api to my project and therefore I need a selective mysql statement bt I always get back

{
    "error": "(1054, u\"Unknown column 'None' in 'where clause'\")"
}

Whats wrong with the code? how do i need to escape id correctly in the mysql select syntax??

```<code>#!/usr/bin/python

from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
from flask.ext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'pi'
app.config['MYSQL_DATABASE_PASSWORD'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_DB'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql.init_app(app)

api = Api(app)

class test(Resource):
    def post(self):
        try:
        # Parse the arguments

        parser = reqparse.RequestParser()
        parser.add_argument('ID', type=str, help='Id of Item')
        args = parser.parse_args()

        id = str(args['ID'])
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM `PowerSystem` WHERE ID=$(id)")

        data = cursor.fetchall()

        items_list=[];
        for item in data:
            i = {
                'ID':str(item[0]),
                'Timestamp':str(item[1]),
                'batteryVoltage':str(item[2]),
                'batteryCurrent':str(item[3]),
                'solarVoltage':str(item[4]),
                'solarCurrent':str(item[5]),
                'loadVoltage':str(item[6]),
                'loadCurrent':str(item[7]),
                'batteryPower':str(item[8]),
                'solarPower':str(item[9]),
                'loadPower':str(item[10]),
                'batteryCharge':str(item[11])
            }
            items_list.append(i)

        return {'StatusCode':'200$(_id)','Items':items_list}

    except Exception as e:
        return {'error': str(e)}
    api.add_resource(test, '/test')

    if __name__ == '__main__':
     app.run(debug=True,host='0.0.0.0')

   app.run(debug=True,host='0.0.0.0')
</code>```

答:
This is the correct and secure way to do it:</p>

```<code>c.execute("SELECT * FROM `PowerSystem` WHERE ID=%s", (id))
</code>```

Title: Python flask rest api

Body:
i like to add a rest api to my project and therefore I need a selective mysql statement bt I always get back

{
    "error": "(1054, u\"Unknown column 'None' in 'where clause'\")"
}

Whats wrong with the code? how do i need to escape id correctly in the mysql select syntax??

#!/usr/bin/python

from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
from flask.ext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'pi'
app.config['MYSQL_DATABASE_PASSWORD'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_DB'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql.init_app(app)

api = Api(app)

class test(Resource):
    def post(self):
        try:
        # Parse the arguments

        parser = reqparse.RequestParser()
        parser.add_argument('ID', type=str, help='Id of Item')
        args = parser.parse_args()

        id = str(args['ID'])
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM `PowerSystem` WHERE ID=$(id)")

        data = cursor.fetchall()

        items_list=[];
        for item in data:
            i = {
                'ID':str(item[0]),
                'Timestamp':str(item[1]),
                'batteryVoltage':str(item[2]),
                'batteryCurrent':str(item[3]),
                'solarVoltage':str(item[4]),
                'solarCurrent':str(item[5]),
                'loadVoltage':str(item[6]),
                'loadCurrent':str(item[7]),
                'batteryPower':str(item[8]),
                'solarPower':str(item[9]),
                'loadPower':str(item[10]),
                'batteryCharge':str(item[11])
            }
            items_list.append(i)

        return {'StatusCode':'200$(_id)','Items':items_list}

    except Exception as e:
        return {'error': str(e)}
    api.add_resource(test, '/test')

    if __name__ == '__main__':
     app.run(debug=True,host='0.0.0.0')

   app.run(debug=True,host='0.0.0.0')

Body:
This is the correct and secure way to do it:

c.execute("SELECT * FROM `PowerSystem` WHERE ID=%s", (id))


问:
No mapping found for HTTP request with URI [/welcome] in DispatcherServlet with name 'dispatcherServlet' in Spring Boot 1.5.3v
Am new to spring boot unable to get the issue resolved.
In below Screenshots i have commented "/hello" which i could access with localhost:1200/hello .But unable to access other controllers as "/welcome" ,"/home" attached screenshots .

SpringApplication class

Controller class

答:
Since your @SpringBootApplication annotation is in com.example.demo, and no basePackage is defined for scanning, it will only scan that package and its nested packages. The easiest way to solve this is to move your controller package.

From this:

```<code>.
└── main
    ├── java
    │   └── com
    │       └── example
    │           ├── controller
    │           │   └── DemoRestController.java
    │           └── demo
    │               └── DemoApplication.java
    └── resources
        └── application.properties
</code>```

To this:

```<code>.
└── main
    ├── java
    │   └── com
    │       └── example
    │           └── demo
    │               ├── controller
    │               │   └── DemoRestController.java
    │               └── DemoApplication.java
    └── resources
        └── application.properties
</code>```

Doc from @ComponentScan :

Either basePackageClasses() or basePackages() (or its alias value())
  may be specified to define specific packages to scan. If specific
  packages are not defined, scanning will occur from the package of the
  class that declares this annotation.

Body:
Since your @SpringBootApplication annotation is in com.example.demo, and no basePackage is defined for scanning, it will only scan that package and its nested packages. The easiest way to solve this is to move your controller package.

From this:

.
└── main
    ├── java
    │   └── com
    │       └── example
    │           ├── controller
    │           │   └── DemoRestController.java
    │           └── demo
    │               └── DemoApplication.java
    └── resources
        └── application.properties

To this:

.
└── main
    ├── java
    │   └── com
    │       └── example
    │           └── demo
    │               ├── controller
    │               │   └── DemoRestController.java
    │               └── DemoApplication.java
    └── resources
        └── application.properties

Doc from @ComponentScan :

Either basePackageClasses() or basePackages() (or its alias value())
  may be specified to define specific packages to scan. If specific
  packages are not defined, scanning will occur from the package of the
  class that declares this annotation.


问:
In C language, Static Variable with pointer access
My question is about Memory and how it is being accessed across a program with multiple C files (Multiple Modules).

file1.h Version 1

```<code>    #ifndef file1_h
    #define file1_h

    typedef struct
    {
      UINT8  var1;
      UINT16 var2;
      UINT16 var3;
    } TestAccess;

    static TestAccess* pLongRangeAccess;

    #endif
</code>```

file1.h Version 2

```<code>    #ifndef file1_h
    #define file1_h

    typedef struct
    {
      UINT8  var1;
      UINT16 var2;
      UINT16 var3;
    } TestAccess_t;

    TestAccess_t* pLongRangeAccess;

    #endif
</code>```

Main.c

```<code>#include "file1.h"

void main(void)
{
  pLongRangeAccess->var1 = 4;
  pLongRangeAccess->var2 = 8;
  pLongRangeAccess->var3 = 16;
}
</code>```

Module1.c
//Needs read/write access to the struct variables

```<code>#include "file1.h"

void module1(void)
{
  pLongRangeAccess->var1 = 5;
  pLongRangeAccess->var2 = 10;
  pLongRangeAccess->var3 = 20;
}
</code>```

Question 1) See "Version1" Does static in keyword make it such that there will be only one copy in heap memory (uninitialized) and therefore only one address of the pointer variable OR would it create 2 static variables with different memory since the header is used in every module?

Question 2) see "Version 2" If static was not declared for the pointer variable, then it would still be in heap memory and there would be one UNIQUE address that could be used to accessed to read and write operations to the members?

Question 3) In version 2 of file1.h if the pointer was declared in Main.c, and the memory location was fixed i.e it was declared as a constant, would it be available for access from any module by de-referencing the memory address location?

答:
I think you are mixing up "memory allocation" with variable declaration and variable definition. I think what you want is to share a variable pLongRangeAccess among different translation units, such that it exists only once in your program. To do that, declare the variable in the header file, and define it once in a single c-file:

```<code>#ifndef file1_h
#define file1_h

typedef struct
{
  UINT8  var1;
  UINT16 var2;
  UINT16 var3;
} TestAccess;

extern TestAccess* pLongRangeAccess;

#endif
</code>```

And then the .c-file:

```<code>// file1.c:
#include "file1.h"
TestAccess* pLongRangeAccess;
</code>```

Note that keyword static, when applied to variables outside any function, means that this variable is private to the respective translation unit; this is mainly for information hiding and for avoiding unintended name clashes with other translation units (from different vendors, probably).

So, if you write

```<code>// file1.c
static TestAccess* pLongRangeAccess;

// file2.c
static TestAccess* pLongRangeAccess;
</code>```

, then translation unit file1 and file2 both have their own private variable pLingRangeAccess, which is not visible to other translation units (regardless if any head file declares the variable as extern). The linker will not complain any "duplicate variable definition" in this case, as - as mentioned - the variables are private to their TU.

If you write, however, the following

```<code>// file1.c
TestAccess* pLongRangeAccess;

// file2.c
TestAccess* pLongRangeAccess;
</code>```

, then both variables become visible to the other translation units, and the linker will complain that variable pLongRangeAccess is defined twice in your program, which is not allowed.

Body:
My question is about Memory and how it is being accessed across a program with multiple C files (Multiple Modules).

file1.h Version 1

    #ifndef file1_h
    #define file1_h

    typedef struct
    {
      UINT8  var1;
      UINT16 var2;
      UINT16 var3;
    } TestAccess;

    static TestAccess* pLongRangeAccess;

    #endif

file1.h Version 2

    #ifndef file1_h
    #define file1_h

    typedef struct
    {
      UINT8  var1;
      UINT16 var2;
      UINT16 var3;
    } TestAccess_t;

    TestAccess_t* pLongRangeAccess;

    #endif

Main.c

#include "file1.h"

void main(void)
{
  pLongRangeAccess->var1 = 4;
  pLongRangeAccess->var2 = 8;
  pLongRangeAccess->var3 = 16;
}

Module1.c
//Needs read/write access to the struct variables

#include "file1.h"

void module1(void)
{
  pLongRangeAccess->var1 = 5;
  pLongRangeAccess->var2 = 10;
  pLongRangeAccess->var3 = 20;
}

Question 1) See "Version1" Does static in keyword make it such that there will be only one copy in heap memory (uninitialized) and therefore only one address of the pointer variable OR would it create 2 static variables with different memory since the header is used in every module?

Question 2) see "Version 2" If static was not declared for the pointer variable, then it would still be in heap memory and there would be one UNIQUE address that could be used to accessed to read and write operations to the members?

Question 3) In version 2 of file1.h if the pointer was declared in Main.c, and the memory location was fixed i.e it was declared as a constant, would it be available for access from any module by de-referencing the memory address location?

Body:
I think you are mixing up "memory allocation" with variable declaration and variable definition. I think what you want is to share a variable pLongRangeAccess among different translation units, such that it exists only once in your program. To do that, declare the variable in the header file, and define it once in a single c-file:

#ifndef file1_h
#define file1_h

typedef struct
{
  UINT8  var1;
  UINT16 var2;
  UINT16 var3;
} TestAccess;

extern TestAccess* pLongRangeAccess;

#endif

And then the .c-file:

// file1.c:
#include "file1.h"
TestAccess* pLongRangeAccess;

Note that keyword static, when applied to variables outside any function, means that this variable is private to the respective translation unit; this is mainly for information hiding and for avoiding unintended name clashes with other translation units (from different vendors, probably).

So, if you write

// file1.c
static TestAccess* pLongRangeAccess;

// file2.c
static TestAccess* pLongRangeAccess;

, then translation unit file1 and file2 both have their own private variable pLingRangeAccess, which is not visible to other translation units (regardless if any head file declares the variable as extern). The linker will not complain any "duplicate variable definition" in this case, as - as mentioned - the variables are private to their TU.

If you write, however, the following

// file1.c
TestAccess* pLongRangeAccess;

// file2.c
TestAccess* pLongRangeAccess;

, then both variables become visible to the other translation units, and the linker will complain that variable pLongRangeAccess is defined twice in your program, which is not allowed.


问:
Visual Studio debug with Browserify
I'm getting up to speed with packaging and using Browserify because I got it to work. I can debug in the browser because the browser maps point to the .JS code.

Is there a way to get the Visual Studio to work with such bundling?

答:
If you mean that you want to debug the JavaScript or TypeScript directly in Visual Studio, I suggest you use the VS2017 which has the new feature:

https://blogs.msdn.microsoft.com/webdev/2016/11/21/client-side-debugging-of-asp-net-projects-in-google-chrome/

A similar issue:

Javascript breakpoints in Visual Studio 2017

Title: Visual Studio debug with Browserify


问:
Unable to create mocks on post request with content-type : application/x-www-form-urlencoded
I am working with mountebank to create mocks for an External REST API
which is a POST request with content-type : application/x-www-form-urlencoded.

The API is of format

https://<url>/dpay/MPmt

and data payload is passed in format msg=01223~20170607114321~ABC~12345~NA~NA

I have to search on the basis of ~ABC~12345~ which would remain constant.

I have used contains, matches and equals predicates but was not able to run them while passing the payload in request body.

However, I was able to get it running when passing payload as a query parameter

https://url/dpay/MPmt?msg=01223~20170607114321~ABC~12345~NA~NA

but can't find a way to get it done when passed in request body.

Any pointers would be really appreciated.

答:
Use the predicate "contains" and pass your matching string only. What I suspect is that you are using

"contains" :
{ "body" : {
   "msg": "~ABC~12345~"
  }
 }

this will look for an msg variable in the request body, instead, use

"contains" : {"body": "~ABC~12345~"}

and it will match it directly in your request body.

I faced the same issue, Hope it works for you.


答:
Check the below code. As I understand, you want to close the .tag-cloud when clicked on close.

$(document).ready(function() {

  $(".film h4.film-title").click(function() {
    $(this).parent().children(".tag-cloud").show();
  });

  $(".fa-close").on('click', function() {
    $(this).parents(".tag-cloud:first").hide();
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tag-cloud {
  display: none;
}</code>```

Open the div here

tag1

tag2

      [Close Button]

```

Title: How to open and close the same div in JQuery

Body:
Check the below code. As I understand, you want to close the .tag-cloud when clicked on close.

$(document).ready(function() {

  $(".film h4.film-title").click(function() {
    $(this).parent().children(".tag-cloud").show();
  });

  $(".fa-close").on('click', function() {
    $(this).parents(".tag-cloud:first").hide();
  });

});

.tag-cloud {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="film">

  <h4 class="film-title">Open the div here</h4>

  <div class="tag-cloud">
    <!-- tag-cloud -->
    <i class="fa fa-2x fa-close"></i>
    <ul>
      <li><a href="">tag1</a></li>
      <li><a href="">tag2</a></li>
    </ul>
    <div class="exit-tags">
      <i class="fa fa-2x fa-close">[Close Button]</i>
      <!-- The close button for the tag-cloud -->
    </div>
  </div>

</div>


问:
How to get text with some specific tags' text together in a tag by scrapy in python?
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

```<code><div class="user-info">
    <p class="user-img">
        something in p tag
    </p>
    <em>text</em> data I want
    <a href="#">
        something in a tag
    </a>
</div>
</code>```

I want to get the text data I want only. But the text is in the tag . So if I use div[contains(@class, "user-info")]/text(), I can get data I want only. If I use div[contains(@class, "user-info")]/node() I get all the tags inside div.user-info, and also div[contains(@class, "user-info")]/node()/text(). So the question is, how can I get the text and the data I want together to be text data I want?

答:
Try to use below XPath to get two required text nodes concatenated:

```<code>concat(//div[@class="user-info"]/em/text(), " ", //div[@class="user-info"]/text()[3])
</code>```

Body:
I am new to scrapy. I want to crawl some data from the web. I got the html document like below.

        something in p tag

    text data I want

        something in a tag

I want to get the text data I want only. But the text is in the tag . So if I use div[contains(@class, "user-info")]/text(), I can get data I want only. If I use div[contains(@class, "user-info")]/node() I get all the tags inside div.user-info, and also div[contains(@class, "user-info")]/node()/text(). So the question is, how can I get the text and the data I want together to be text data I want?

Body:
Try to use below XPath to get two required text nodes concatenated:

concat(//div[@class="user-info"]/em/text(), " ", //div[@class="user-info"]/text()[3])


问:
PHP: switch() default for all?
I have this:

```<code>case true:

    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
    break;

    default:
    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
    break;
</code>```

I am trying to ONLY if it's true, then show normal else do READONLY.

The switch is checking from a function

```<code>switch( ( check_friend_state($showU["id"], 'friend') ) )
</code>```

And I tried to echo the function, and it returned err2 and not true, so why does it run true?

I also tried if/else

```<code>if(check_friend_state($showU["id"], 'friend') == true){

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
}else{
echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
}
</code>```

But as said previously it returns "err2" and still it runs true?

My function at the return:

```<code>if($USER == $uID){ // not yourself
return "err1";
}elseif( $checkIsFriend->rowCount() == 1 ){  // already friends
return "err2";
}elseif( $checkAlready->rowCount() == 1 ){ // already send a request
return "err3";
}elseif( $checkBlock->rowCount() == 1 ){ // blocked
return "err4";
}else{
return true;
}
</code>```

答:
This is an artifact of PHP converting types in comparisons for you.  Numbers != 0 and non-empty strings are considered to be true values when converted to booleans.

You can prevent this by using === instead of ==.

Title: PHP: switch() default for all?

Body:
I have this:

case true:

    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
    break;

    default:
    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
    break;

I am trying to ONLY if it's true, then show normal else do READONLY.

The switch is checking from a function

switch( ( check_friend_state($showU["id"], 'friend') ) )

And I tried to echo the function, and it returned err2 and not true, so why does it run true?

I also tried if/else

if(check_friend_state($showU["id"], 'friend') == true){

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
}else{
echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
}

But as said previously it returns "err2" and still it runs true?

My function at the return:

if($USER == $uID){ // not yourself
return "err1";
}elseif( $checkIsFriend->rowCount() == 1 ){  // already friends
return "err2";
}elseif( $checkAlready->rowCount() == 1 ){ // already send a request
return "err3";
}elseif( $checkBlock->rowCount() == 1 ){ // blocked
return "err4";
}else{
return true;
}


问:
Why return None when doing recursion?
I'm doing this problem Add Digits in recursion way. Why does it return None?</p>

```<code>def addDigits(num):
    """
    :type num: int
    :rtype: int
    """
    shit = str(num)
    n = len(shit)
    if n == 1:
        return num
    else:
        num = 0
        for i in xrange(n):
            num += int(shit[i])
        addDigits(num)
</code>```

答:
You need to return the value of the recursive call in the last line:

```<code>return addDigits(num)
</code>```

Without such a return you silently return None

Title: Why return None when doing recursion?

Body:
I'm doing this problem Add Digits in recursion way. Why does it return None?

def addDigits(num):
    """
    :type num: int
    :rtype: int
    """
    shit = str(num)
    n = len(shit)
    if n == 1:
        return num
    else:
        num = 0
        for i in xrange(n):
            num += int(shit[i])
        addDigits(num)

Body:
You need to return the value of the recursive call in the last line:

return addDigits(num)

Without such a return you silently return None


问:
Published extension doesn't work like in development
I'm currently trying to develop an extension for VSCode.

In development it works fine.
However on another PC which downloads from the marketplace my extension doesn't work.

The error Running the contributed command:'dynamicsnav.compile_obj' failed. pops up on every command run.

Is it possible to debug my extension on another machine which downloads my extension?

Sourcecode of extension

Vscode marketplace

答: You don't have the full debugging abilities but since vscode (and Electron on which vscode is based) is essentially a browser you can use the developer tools (Help -> Developer Tools) to see error messages. </p>


问:
How to get String[] outside OnCreate()
Here I'm using the following code to create a string current[] using for loop:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imageactivity);

    Intent intent = getIntent();
    String jsonArray = intent.getStringExtra("jsonArray");
   try {
        JSONArray array = new JSONArray(jsonArray);
        for (int i = 0; i < array.length(); i++) {
           JSONObject obj = array.getJSONObject(i);
            String current_name[] = { obj.getString("current_name") }; // array
       }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

// Log.e(TAG,"VALUES" + Arrays.toString(current_name));
</code>```

Now I want to call this current_name[] outside OnCreate or some other method. By using this code I can't Log outside OnCreate. So please help me to solve this issue. Answers will be appreciated.

答:
Declare the array as a member of the activity and in the onCreate initialize it only</p>

```<code>try {
    JSONArray array = new JSONArray(jsonArray);
    for (int i = 0; i < array.length(); i++) {
       JSONObject obj = array.getJSONObject(i);
        current_name[i] =  obj.getString("current_name");
   }
} catch (JSONException e) {
    e.printStackTrace();
}
</code>```

Title: How to get String[] outside OnCreate()

Body:
Here I'm using the following code to create a string current[] using for loop:

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

    Intent intent = getIntent();
    String jsonArray = intent.getStringExtra("jsonArray");
   try {
        JSONArray array = new JSONArray(jsonArray);
        for (int i = 0; i < array.length(); i++) {
           JSONObject obj = array.getJSONObject(i);
            String current_name[] = { obj.getString("current_name") }; // array
       }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

// Log.e(TAG,"VALUES" + Arrays.toString(current_name));

Now I want to call this current_name[] outside OnCreate or some other method. By using this code I can't Log outside OnCreate. So please help me to solve this issue. Answers will be appreciated.

Body:
Declare the array as a member of the activity and in the onCreate initialize it only

try {
    JSONArray array = new JSONArray(jsonArray);
    for (int i = 0; i < array.length(); i++) {
       JSONObject obj = array.getJSONObject(i);
        current_name[i] =  obj.getString("current_name");
   }
} catch (JSONException e) {
    e.printStackTrace();
}


问:
Playing only the audio 1, not 2, 3 and 4
```<code>   var hello = intent.extras["i"]

    when(hello){

        1-> {
            mediaPlayer = MediaPlayer()
            var i = R.raw.ques1
            mediaPlayer = MediaPlayer.create(this,i)
            mediaPlayer!!.start()
            if (mediaPlayer == null) {
                mediaPlayer!!.stop()
                mediaPlayer!!.release()
                MediaRecorderReady()
            }

        }

        2-> {
            mediaPlayer = MediaPlayer()
            var i = R.raw.ques2
            mediaPlayer ==MediaPlayer.create(this,i)
            mediaPlayer!!.start()

        }

        3->{
            mediaPlayer = MediaPlayer()
            var i = R.raw.ques3
            mediaPlayer ==MediaPlayer.create(this,i)
            mediaPlayer!!.start()

        }

        4->{
            mediaPlayer = MediaPlayer()
            var i = R.raw.ques4
            mediaPlayer ==MediaPlayer.create(this,i)
            mediaPlayer!!.start()

        }

    }
</code>```

Error //06-08 00:48:38.557 10334-10334/com.example.admin.lastmedpro
  E/MediaPlayer: start called in state 1 06-08 00:48:38.557
  10334-10334/com.example.admin.lastmedpro E/MediaPlayer: error (-38, 0)
  06-08 00:48:38.573 10334-10334/com.example.admin.lastmedpro
  E/MediaPlayer: Should have subtitle controller already set 06-08
  00:48:38.573 10334-10334/com.example.admin.lastmedpro E/MediaPlayer:
  Error (-38,0)

答:
```<code> mediaPlayer ==MediaPlayer.create(this,i)
</code>```

Why do you use == instead of = ? It's error (exactly 2,3 and 4 case).

Plus you don't need these four lines:

```<code>mediaPlayer = MediaPlayer()
</code>```

Body:
   var hello = intent.extras["i"]

    when(hello){

        1-> {
            mediaPlayer = MediaPlayer()
            var i = R.raw.ques1
            mediaPlayer = MediaPlayer.create(this,i)
            mediaPlayer!!.start()
            if (mediaPlayer == null) {
                mediaPlayer!!.stop()
                mediaPlayer!!.release()
                MediaRecorderReady()
            }

        }

        2-> {
            mediaPlayer = MediaPlayer()
            var i = R.raw.ques2
            mediaPlayer ==MediaPlayer.create(this,i)
            mediaPlayer!!.start()

        }

        3->{
            mediaPlayer = MediaPlayer()
            var i = R.raw.ques3
            mediaPlayer ==MediaPlayer.create(this,i)
            mediaPlayer!!.start()

        }

        4->{
            mediaPlayer = MediaPlayer()
            var i = R.raw.ques4
            mediaPlayer ==MediaPlayer.create(this,i)
            mediaPlayer!!.start()

        }

    }

Error //06-08 00:48:38.557 10334-10334/com.example.admin.lastmedpro
  E/MediaPlayer: start called in state 1 06-08 00:48:38.557
  10334-10334/com.example.admin.lastmedpro E/MediaPlayer: error (-38, 0)
  06-08 00:48:38.573 10334-10334/com.example.admin.lastmedpro
  E/MediaPlayer: Should have subtitle controller already set 06-08
  00:48:38.573 10334-10334/com.example.admin.lastmedpro E/MediaPlayer:
  Error (-38,0)

Body:
 mediaPlayer ==MediaPlayer.create(this,i)

Why do you use == instead of = ? It's error (exactly 2,3 and 4 case).

Plus you don't need these four lines:

mediaPlayer = MediaPlayer()


问:
How can I structure Firebase Realtime Database Rules to allow sending of "invite" URLs to non-users to allow access to protected user-data structures?
Consider the following protected "room" data structure at /rooms/room1:

Data:

```<code>{
  rooms: {
    room1: {
      content: "hello world",
      authorizedUsers: {
        "UidOfUserA": true,
        "UidOfUserB": true
      }
    }
  }
}
</code>```

Rules:

```<code>{
  "rules": {
    "rooms": {
      "$room": {
        ".read": "data.child('authorizedUsers').hasChild(auth.uid)",
        ".write": "data.child('authorizedUsers').hasChild(auth.uid)"
      }
    }
  }
}
</code>```

Currently, UserA and UserB can read and write data to /rooms/room1. Assume that UserA was able to allow UserB to join because UserA knew UserB's UID.

However, if UserA wants to invite someone who does not yet have an account, by generating a URL and sending it to a friend (not necessarily by email,) this design needs to be expanded on.

How can I structure my rules to allow for this?

答:
One possible solution I can think of would be:

allow users to write to their own private sandbox at /users/$uid/ (so that they can set a value in /users/$uid/activeInviteToken)

expand on the room rules to also allow users to write to /rooms/$room/ if their /users/$uid/activeInviteToken is found as a child of /rooms/$room/inviteTokens/

The workflow would then be:

UserA adds a new key to /rooms/room1/inviteTokens/ (assume it's /rooms/room1/inviteTokens/inviteToken1)

UserA generates a link with the invite token and the room name and sends it to their friend; e.g. http://example.com/?roomId=room1&inviteToken=inviteToken1

after UserC signs up, they write their inviteToken to /users/UidOfUserC/activeInviteToken = "inviteToken1"

finally, they add /rooms/room1/authorizedUsers/UidOfUserC, giving themselves access independent of the inviteToken

While not strictly necessary, completing step 4 allows the user to:

change their activeInviteToken to something else, so that they can accept an invite to another room, without losing access to room1; and

expire old inviteTokens

However, this seems overly-complicated, especially the two-step write involving /users/$uid/activeInviteToken before adding themselves to /rooms/room1/authorizedUsers.

Body:
Consider the following protected "room" data structure at /rooms/room1:

Data:

{
  rooms: {
    room1: {
      content: "hello world",
      authorizedUsers: {
        "UidOfUserA": true,
        "UidOfUserB": true
      }
    }
  }
}

Rules:

{
  "rules": {
    "rooms": {
      "$room": {
        ".read": "data.child('authorizedUsers').hasChild(auth.uid)",
        ".write": "data.child('authorizedUsers').hasChild(auth.uid)"
      }
    }
  }
}

Currently, UserA and UserB can read and write data to /rooms/room1. Assume that UserA was able to allow UserB to join because UserA knew UserB's UID.

However, if UserA wants to invite someone who does not yet have an account, by generating a URL and sending it to a friend (not necessarily by email,) this design needs to be expanded on.

How can I structure my rules to allow for this?


问:
How can we access this json key?
```<code>[
  {
    "docId": "58d8f38cd2f554fdfca4fd18",
    "__v": 8,
    "clinicDetails": {
      "5908e342236dee7e7364698e": {
        "appointmentSlots": {
          "sat": {
            "5908e342236dee7e73646a44": {
              "bookFlag": true,
              "endTime": "07:00PM",
              "startTime": "06:30PM"
            },
            "5908e342236dee7e73646a43": {
              "bookFlag": true,
              "endTime": "06:30PM",
              "startTime": "06:00PM"
            },
.......
</code>```

full file https://docs.google.com/document/d/1FK1NEY1Vmjzv2gBtleFquA0VMpfYGf9FaMyblPr8vws/edit?usp=sharing

i need to access these ids like 5908e342236dee7e73646a44 before slot details i am using angular for scripting

答:
var jsonObject = angular.fromJson(yourJsonString)

That will transform your Json to an object. Then you can iterate over any field of the object an get keys or values.

```<code>angular.forEach(jsonObject.whatever, function(value, key) {
    console.log('key : ', key);
    console.log('value : ', value);
});
</code>```

Get key from JSON for API request

Title: How can we access this json key?

Body:
[
  {
    "docId": "58d8f38cd2f554fdfca4fd18",
    "__v": 8,
    "clinicDetails": {
      "5908e342236dee7e7364698e": {
        "appointmentSlots": {
          "sat": {
            "5908e342236dee7e73646a44": {
              "bookFlag": true,
              "endTime": "07:00PM",
              "startTime": "06:30PM"
            },
            "5908e342236dee7e73646a43": {
              "bookFlag": true,
              "endTime": "06:30PM",
              "startTime": "06:00PM"
            },
.......

full file https://docs.google.com/document/d/1FK1NEY1Vmjzv2gBtleFquA0VMpfYGf9FaMyblPr8vws/edit?usp=sharing

i need to access these ids like 5908e342236dee7e73646a44 before slot details i am using angular for scripting

Body:
var jsonObject = angular.fromJson(yourJsonString)

That will transform your Json to an object. Then you can iterate over any field of the object an get keys or values.

angular.forEach(jsonObject.whatever, function(value, key) {
    console.log('key : ', key);
    console.log('value : ', value);
});

Get key from JSON for API request