问:
spark: java.io.IOException: No space left on device [again!]
I am getting the java.io.IOException: No space left on device that occurs after running a simple query in sparklyr. I use both last versions of Spark (2.1.1) and Sparklyr

```<code>df_new <-spark_read_parquet(sc, "/mypath/parquet_*", name = "df_new", memory = FALSE)

myquery <- df_new %>% group_by(text) %>% summarize(mycount = n()) %>%
  arrange(desc(mycount)) %>% head(10)

#this FAILS
get_result <- collect(myquery)
</code>```

I do have set both

spark.local.dir <- "/mypath/"

spark.worker.dir <- "/mypath/"

using the usual

```<code>config <- spark_config()

config$`spark.executor.memory` <- "100GB"
config$`spark.executor.cores` <- "3"
config$`spark.local.dir` <- "/mypath/"
config$`spark.worker.dir` <- "mypath/"
config$`spark.cores.max`<- "2000"
config$`spark.default.parallelism`<- "4"
config$`spark.total-executor-cores`<- "80"
config$`sparklyr.shell.driver-memory` <- "100G"
config$`sparklyr.shell.executor-memory` <- "100G"
config$`spark.yarn.executor.memoryOverhead` <- "100G"
config$`sparklyr.shell.num-executors` <- "90"
config$`spark.memory.fraction` <- "0.2"

  Sys.setenv(SPARK_HOME="mysparkpath")
  sc <- spark_connect(master = "spark://mynode", config = config)
</code>```

where mypath has more than 5TB of disk space (I can see these options in the Environment tab). I tried a similar command in Pyspark and it failed the same way (same error).

By looking at the  Stages tab in Spark, I see that the error occurs when shuffle write is about 60 GB. (input is about 200GB). This is puzzling given that I have plenty of space available. I have have looked at the other SO solutions already...

The cluster job is started with magpie https://github.com/LLNL/magpie/blob/master/submission-scripts/script-sbatch-srun/magpie.sbatch-srun-spark

Every time I start a Spark job, I see a directory called spark-abcd-random_numbers in my /mypath folder. but the size of the files in there is very small (nowhere near the 60GB shuffle write)

there are about 40 parquet files. each is 700K (original csv files were 100GB) They contain strings essentially.

cluster is 10 nodes, each has 120GB RAM and 20 cores.

What is the problem here?
Thanks!!

答:
Once you set the parameter, you can see the new value of spark.local.dir in Spark environment UI. But it doesn't reflect.

Even I faced the similar problem. After setting this parameter, I restarted the machines and then started working.

Body:
I am getting the java.io.IOException: No space left on device that occurs after running a simple query in sparklyr. I use both last versions of Spark (2.1.1) and Sparklyr

df_new <-spark_read_parquet(sc, "/mypath/parquet_*", name = "df_new", memory = FALSE)

myquery <- df_new %>% group_by(text) %>% summarize(mycount = n()) %>%
  arrange(desc(mycount)) %>% head(10)

#this FAILS
get_result <- collect(myquery)

I do have set both

spark.local.dir <- "/mypath/"

spark.worker.dir <- "/mypath/"

using the usual

config <- spark_config()

config$`spark.executor.memory` <- "100GB"
config$`spark.executor.cores` <- "3"
config$`spark.local.dir` <- "/mypath/"
config$`spark.worker.dir` <- "mypath/"
config$`spark.cores.max`<- "2000"
config$`spark.default.parallelism`<- "4"
config$`spark.total-executor-cores`<- "80"
config$`sparklyr.shell.driver-memory` <- "100G"
config$`sparklyr.shell.executor-memory` <- "100G"
config$`spark.yarn.executor.memoryOverhead` <- "100G"
config$`sparklyr.shell.num-executors` <- "90"
config$`spark.memory.fraction` <- "0.2"

  Sys.setenv(SPARK_HOME="mysparkpath")
  sc <- spark_connect(master = "spark://mynode", config = config)

where mypath has more than 5TB of disk space (I can see these options in the Environment tab). I tried a similar command in Pyspark and it failed the same way (same error).

By looking at the  Stages tab in Spark, I see that the error occurs when shuffle write is about 60 GB. (input is about 200GB). This is puzzling given that I have plenty of space available. I have have looked at the other SO solutions already...

The cluster job is started with magpie https://github.com/LLNL/magpie/blob/master/submission-scripts/script-sbatch-srun/magpie.sbatch-srun-spark

Every time I start a Spark job, I see a directory called spark-abcd-random_numbers in my /mypath folder. but the size of the files in there is very small (nowhere near the 60GB shuffle write)

there are about 40 parquet files. each is 700K (original csv files were 100GB) They contain strings essentially.

cluster is 10 nodes, each has 120GB RAM and 20 cores.

What is the problem here?
Thanks!!


来源: stackexchange

问:
Can an Iframe load its contents at the server side rather than client side?
I know that setting runat="server" and specifying an id for an iframe control, makes it accessible on the server side but what I need is that the iframe source contents get loaded at server side not client side.

Is it possible?

Why do I need it this way?

Currently my iframe source site is configured for ntlm authentication and sso which means it would read my windows credentials whereas I'd need it reads the credentials provided by the site which hosts that iframe.

Thanks

答: No that cannot be done. It is not the way things work. If you need to load content on the server side, you can use the WebRequest class. But I doubt that that is what you want. I think you need to rethink your application design.

ContentLicense: CC BY-SA 2.5


问:
C# ASP.NET project with Facebook login - not working
I want to create a ASP.NET project (Single Page Application) and activate Facebook login. But now 2 days later I can not get it work!

I have:
Visual Studio 2015

This is my steps:

Create a new ASP.NET 4.6 (Single Page Application) -project.

Uncomment this and added appid and appsecret (fake here):

```<code>app.UseFacebookAuthentication(
    appId: "5675675657567567",
    appSecret: "346n3636n34n6346n346n346n346n346");
</code>```

Created a new Facebook app with this settings:

```<code>-Client OAuth Login: on

-Web OAuth Login: on

-App Domains: localhost

-Valid OAuth redirect URIs: http://localhost:63496/signin-facebook
</code>```

And added the real appid and secret.

When I click on the facebook login button, i can login to facebook but i just redirect back to my homepage and nothing happens, I am not logged in at all. Next time I click on the facebook login button it seems that i am already logged in on facebook so I just redirect back again directly.

So the question is, how can I login to my homepage via Facebook? Can I not login correctly in debug-mode?

答:
Simply update the package Windows.Owin.Security.Facebook to the latest version (3.1.0)

Further, in the Facebook application update the "Valid OAuth redirect URIs" to "http://localhost:xxxx/signin-facebook" (where xxxx represents the port number) every thing works...

ContentLicense: CC BY-SA 3.0

Body:
I want to create a ASP.NET project (Single Page Application) and activate Facebook login. But now 2 days later I can not get it work!

I have:
Visual Studio 2015

This is my steps:

Create a new ASP.NET 4.6 (Single Page Application) -project.

Uncomment this and added appid and appsecret (fake here):

app.UseFacebookAuthentication(
    appId: "5675675657567567",
    appSecret: "346n3636n34n6346n346n346n346n346");

Created a new Facebook app with this settings:

-Client OAuth Login: on

-Web OAuth Login: on

-App Domains: localhost

-Valid OAuth redirect URIs: http://localhost:63496/signin-facebook

And added the real appid and secret.

When I click on the facebook login button, i can login to facebook but i just redirect back to my homepage and nothing happens, I am not logged in at all. Next time I click on the facebook login button it seems that i am already logged in on facebook so I just redirect back again directly.

So the question is, how can I login to my homepage via Facebook? Can I not login correctly in debug-mode?


问:
Dynamic list box using jquery
I have never worked with Jquery and researched that the solution to my problem is through jquery only, So can any one help..

I have 4 list box having data that i need to fetch from sql database. two list box have data from  table A and other two have data from table B. Basically my form will give two options to select so i created two list box for each item.like two preferred games(football,basketball,tennis ... etc) on two preferred days (like Mon,Tue,Wed...etc)

Now the challenge I am facing is how to write a jquery so that if football is chosen as first game and Mon is chosen as preferred day, then on second option these two should not be available on list items.

答:
Take a look http://www.jqueryscript.net/form/Dynamic-Dependent-Dropdown-List-Plugin-With-jQuery-linkedSelect.html and  https://hungred.com/how-to/tutorial-jquery-select-box-manipulation-plugin/
it has some info about dynamic stacks on jquery </p>

Title: Dynamic list box using jquery


问:
Entity Framework 6 exception: "The context cannot be used while the model is being created"
I'm a bit new when it is coming to Entity Framework 6 from the old style of ADO.NET, so bear with me here.

I'm trying to create a new WPF MVVM project and also a few WinForms that will use just straight out DBContext without data-binding with the EF 6.

Using Visual Studio 2013 Entity framework wizard, I created a code-first by reverse engineer a current database on our business server. I then separated the data model classes from the context

This is the DbContext code:

```<code>namespace EFModels
{
    public partial class MyDataContext : DbContext
    {
        public MyDataContext () : base("name=MyDataContext")
        {
        }

        public virtual DbSet<Calibration> Calibrations { get; set; }
        public virtual DbSet<OrderDetail> OrderDetails { get; set; }
        public virtual DbSet<OrderHistory> OrderHistories { get; set; }
        public virtual DbSet<WorkDetail> WorkDetails { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<WorkDetail>()
                    .HasMany(e => e.Calibrations)
                    .WithOptional(e => e.WorkDetail)
                    .HasForeignKey(e => e.WorkID);
        }
    }
}
</code>```

I've separated the data classes in a separate namespace, for example:

```<code>namespace MyDataDomain
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class OrderDetail
    {
        public OrderDetail()
        {
            Calibrations = new HashSet<Calibration>();
            JournalEntryDatas = new HashSet<JournalEntryData>();
            OrderHistories = new HashSet<OrderHistory>();
            WorkDetails = new HashSet<WorkDetail>();
        }

        [Key]
        public long OrderID { get; set; }

        [StringLength(50)]
        public string PONumber { get; set; }

        [Column(TypeName = "date")]
        public DateTime? Due { get; set; }

        [Column(TypeName = "date")]
        public DateTime? OrderDate { get; set; }

        [Column(TypeName = "date")]
        public DateTime? ShipDate { get; set; }

        [Column(TypeName = "text")]
        public string Comment { get; set; }

        public int? EnterByID { get; set; }

        public virtual ICollection<Calibration> Calibrations { get; set; }

        public virtual ICollection<JournalEntryData> JournalEntryDatas { get; set; }
        public virtual ICollection<OrderHistory> OrderHistories { get; set; }
        public virtual ICollection<WorkDetail> WorkDetails { get; set;      }
    }
}
</code>```

The rest of the classes are in similiar style, but when using the foreign key constraint it has something like this:

```<code>public virtual OrderDetail OrderDetail { get; set; }
</code>```

since in our little world, it will revolve around the Orders.

And the app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
  <connectionStrings>
    <add name="MyDataContext" connectionString="data source=BIZSERVER\SQL2008R2DB;initial catalog=Company;persist security info=True;user id=DaBossMan;password=none_of_your_damn_business;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
```

<p>So when I do this:</p>

```var context = New MyDataContext();
var list1 = context.JournalEntryDatas.ToList();
var list2 = context.OrderHistories.ToList();
```

<p>An exception is thrown:</p>

<blockquote>
  <p>The context cannot be used while the model is being created. This
  exception may be thrown if the context is used inside the
  <code>OnModelCreating</code> method or if the same context instance is accessed by
  multiple threads concurrently. Note that instance members of <code>DbContext</code>
  and related classes are not guaranteed to be thread safe.</p>
</blockquote>

<p>I'm going nuts here trying to figure out what I can do, and I've been reading that maybe doing a task factory could help, so then how can I use it to get the data from each table so I can populate the lists?</p>

<p>OR is there another alternative or a workaround that I can use?</p>

<p>EDIT: Here is the FULL stacktrace as requested (by Andez):</p>

```System.InvalidOperationException was caught
HResult=-2146233079
Message=The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
Source=EntityFramework
StackTrace:
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at MichellControls.JournalDataListView.JournalDataListView_Load(Object sender, EventArgs e) in c:\Users\Steve\Projects\Visual Studio 2013\Projects\MyControls\WinFormControls\JournalDataListView.cs:line 35
InnerException:
    // (there wasn't any InnerException)
```

答:
You said you (were) new to entity framework, so perhaps it is worth pointing out that DbContexts are not supposed to be shared and reused.  Usually you'll want to create, use, and dispose a DbContext within a single unit of work.

In other words, you shouldn't be "sharing" the DbContext (e.g. creating just one at startup and using it in multiple places, etc.  You mentioned trying to create a "thread-safe wrapper" -- you definitely shouldn't be trying to access it from multiple threads (each operation would have its own DbContext)

Body:
I'm a bit new when it is coming to Entity Framework 6 from the old style of ADO.NET, so bear with me here.

I'm trying to create a new WPF MVVM project and also a few WinForms that will use just straight out DBContext without data-binding with the EF 6.

Using Visual Studio 2013 Entity framework wizard, I created a code-first by reverse engineer a current database on our business server. I then separated the data model classes from the context

This is the DbContext code:

namespace EFModels
{
    public partial class MyDataContext : DbContext
    {
        public MyDataContext () : base("name=MyDataContext")
        {
        }

        public virtual DbSet<Calibration> Calibrations { get; set; }
        public virtual DbSet<OrderDetail> OrderDetails { get; set; }
        public virtual DbSet<OrderHistory> OrderHistories { get; set; }
        public virtual DbSet<WorkDetail> WorkDetails { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<WorkDetail>()
                    .HasMany(e => e.Calibrations)
                    .WithOptional(e => e.WorkDetail)
                    .HasForeignKey(e => e.WorkID);
        }
    }
}

I've separated the data classes in a separate namespace, for example:

namespace MyDataDomain
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class OrderDetail
    {
        public OrderDetail()
        {
            Calibrations = new HashSet<Calibration>();
            JournalEntryDatas = new HashSet<JournalEntryData>();
            OrderHistories = new HashSet<OrderHistory>();
            WorkDetails = new HashSet<WorkDetail>();
        }

        [Key]
        public long OrderID { get; set; }

        [StringLength(50)]
        public string PONumber { get; set; }

        [Column(TypeName = "date")]
        public DateTime? Due { get; set; }

        [Column(TypeName = "date")]
        public DateTime? OrderDate { get; set; }

        [Column(TypeName = "date")]
        public DateTime? ShipDate { get; set; }

        [Column(TypeName = "text")]
        public string Comment { get; set; }

        public int? EnterByID { get; set; }

        public virtual ICollection<Calibration> Calibrations { get; set; }

        public virtual ICollection<JournalEntryData> JournalEntryDatas { get; set; }
        public virtual ICollection<OrderHistory> OrderHistories { get; set; }
        public virtual ICollection<WorkDetail> WorkDetails { get; set;      }
    }
}

The rest of the classes are in similiar style, but when using the foreign key constraint it has something like this:

public virtual OrderDetail OrderDetail { get; set; }

since in our little world, it will revolve around the Orders.

And the app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
  <connectionStrings>
    <add name="MyDataContext" connectionString="data source=BIZSERVER\SQL2008R2DB;initial catalog=Company;persist security info=True;user id=DaBossMan;password=none_of_your_damn_business;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

So when I do this:

var context = New MyDataContext();
var list1 = context.JournalEntryDatas.ToList();
var list2 = context.OrderHistories.ToList();

An exception is thrown:

The context cannot be used while the model is being created. This
  exception may be thrown if the context is used inside the
  OnModelCreating method or if the same context instance is accessed by
  multiple threads concurrently. Note that instance members of DbContext
  and related classes are not guaranteed to be thread safe.

I'm going nuts here trying to figure out what I can do, and I've been reading that maybe doing a task factory could help, so then how can I use it to get the data from each table so I can populate the lists?

OR is there another alternative or a workaround that I can use?

EDIT: Here is the FULL stacktrace as requested (by Andez):

System.InvalidOperationException was caught
HResult=-2146233079
Message=The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
Source=EntityFramework
StackTrace:
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at MichellControls.JournalDataListView.JournalDataListView_Load(Object sender, EventArgs e) in c:\Users\Steve\Projects\Visual Studio 2013\Projects\MyControls\WinFormControls\JournalDataListView.cs:line 35
InnerException:
    // (there wasn't any InnerException)

ContentLicense: CC BY-SA 4.0


问:
Gap between contents
I am trying to make a news website(in Bangla language)... so I am having a trouble.There is an image below for it

I want to fill the red marked area. How can I do it? The css of news content's is

```<code>.main-news {
    vertical-align: top;
    margin-top: 0;
    width: 33.1%;
    height: auto;
    overflow: auto;
    word-wrap: break-word;
    border: 1px solid #ccc;
    display: inline-block;
}
</code>```

Thanks in advance

答:
I suggest putting a specific size to your image and height to your news block</p>

```<code> .main-news {
    vertical-align: top;
    margin-top: 0;
    width: 33.1%;
    height: 200px;    // new code
    overflow: hidden; // new code
    overflow: auto;
    word-wrap: break-word;
    border: 1px solid #ccc;
    display: inline-block;
}
.main-news img{// new code
  width: 20px;
  height: 20px;
}
</code>```

Title: Gap between contents

Body:
I am trying to make a news website(in Bangla language)... so I am having a trouble.There is an image below for it

I want to fill the red marked area. How can I do it? The css of news content's is

.main-news {
    vertical-align: top;
    margin-top: 0;
    width: 33.1%;
    height: auto;
    overflow: auto;
    word-wrap: break-word;
    border: 1px solid #ccc;
    display: inline-block;
}

Thanks in advance

Body:
I suggest putting a specific size to your image and height to your news block

 .main-news {
    vertical-align: top;
    margin-top: 0;
    width: 33.1%;
    height: 200px;    // new code
    overflow: hidden; // new code
    overflow: auto;
    word-wrap: break-word;
    border: 1px solid #ccc;
    display: inline-block;
}
.main-news img{// new code
  width: 20px;
  height: 20px;
}


问:
How can I tell the filetype of images without extension? How do they work?
I am dealing with images on the web that come without a file extension, like this:

```<code>https://static1.squarespace.com/static/52a74d9ae4b0253945d2aee9/t/52ed63b1e4b04368c021b921/1463088116168/?format=500w
</code>```

Images like these can be found, e.g., on websites made with squarespace, like this demo: https://bedford-demo.squarespace.com/

I'm trying to download these images and store them on my server, using PHP. But how can I find out the actual URL of those images? How does this work? And how can I tell the filetype of this image? What is this sorcery?

Any hints are appreciated!

答:
Quick answer:

To find out the Content-Type returned for any URL, look at this answer:

Get Content-Type of requested URL in PHP

Why you need the Content-Type:

Just like how not every webpage on the internet has an URL that ends with .html, images are not required to have an "extension" in their URL either.

What determines whether the browser will treat the data retrieved from the URL as an image is the Content-Type header in the HTTP response.

The URL you posted returns the following HTTP headers:

For HTML documents the Content-Type is text/html. You can inspect the headers as you browse by opening the Network tab of the developer console in your browser. Look for the "response headers".

Body:
I am dealing with images on the web that come without a file extension, like this:

https://static1.squarespace.com/static/52a74d9ae4b0253945d2aee9/t/52ed63b1e4b04368c021b921/1463088116168/?format=500w

Images like these can be found, e.g., on websites made with squarespace, like this demo: https://bedford-demo.squarespace.com/

I'm trying to download these images and store them on my server, using PHP. But how can I find out the actual URL of those images? How does this work? And how can I tell the filetype of this image? What is this sorcery?

Any hints are appreciated!


问:
Converting string from MSSQL to MySQL
I have an app that is reading from a SQL DB and writing to MySQL. This app is used to migrate data for a client. While testing I'm encountering an issue with a single record and I'm stumped. I've tested various suggestions from this site in terms of using the C# Encoding class and have tried to convert it each time with no success on this single record.

The SQL Collation is SQL_Latin1_General_CP1_CI_AS the MySQL collation is latin1_general_ci a sample of the code (in a foreach loop) is below:

```<code>foreach(var pgObj in PgObjList)
{
    //byte[] bytes = Encoding.Default.GetBytes(pgObj.Description);
    //pgObj.Description = Encoding.ASCII.GetString(bytes);

    byte[] utf8Bytes = Encoding.UTF8.GetBytes(pgObj.Description);
    byte[] isoBytes = Encoding.Convert(Encoding.ASCII, Encoding.UTF8, utf8Bytes);
    string uf8converted = Encoding.UTF8.GetString(isoBytes);

    string insertSQL = @"INSERT INTO `mainsite`.`sf_root_items`
                        (`ID`,
                        `LoweredName`,
                        `MenuName`,
                        `Title`,
                        `Description`,
                        `PageType`,
                        `ExternalUrl`
                        )
                        VALUES
                        ('" + pgObj.ID + @"',
                        '" + pgObj.LoweredName + @"',
                        '" + pgObj.MenuName + @"',
                        '" + pgObj.Title + @"',
                        '" + pgObj.Description + @"',
                        '" + pgObj.PageType + @"',
                        '" + pgObj.ExternalUrl + @"'
                        );";
    string outputMsg;
    // more code here to execute the MySQL statement
}
</code>```

The best result I got was converting to ASCII (the commented code) and that stored the text in what looked like Chinese characters. There was no exception but when I run it any other way I get an exception with this record.

Exception:

```<code>MySQL Exception on record#28/r/n
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'il vous plaît (RSVP)',
                                                '0',
             ' at line 15
       at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
       at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
       at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
       at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
       at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
       at SharepointImportDL.SharepointContentImport.GetSitefinityContent.addRootItems(List`1 PgObjList, String WPConnectionString) in C:\Users\Administrator\Source\Repos\TestBinaryWriter\Test Binary Writer\SharepointImportDL\SharepointContentImport\GetSitefinityContent.cs:line 986
</code>```

Line 986 is the SQL execution: int output = cmd.ExecuteNonQuery();

It may also be worth noting that the string that I'm inserting is from a nvarchar column (MSSQL) and into a varchar (MySQL) column

Ironically, the string is a simple "Répondez s'il vous plaît (RSVP)" (I want to punch the pretentious person who had to use the French text) so it's not likely I'll encounter it again but clearly I need to handle this possibility.

答:
Escape strings (eg, pgObj.Description) before building the SQL (string insertSQL).  Otherwise you get syntax error from things like

```<code>, 'Répondez s'il vous plaît (RSVP)',
</code>```

Notice how there is a single quote inside of single quotes?  Also notice how the error pointed at the problem:

```<code>... syntax to use near 'il vous plaît (RSVP)',
</code>```

Title: Converting string from MSSQL to MySQL

Body:
I have an app that is reading from a SQL DB and writing to MySQL. This app is used to migrate data for a client. While testing I'm encountering an issue with a single record and I'm stumped. I've tested various suggestions from this site in terms of using the C# Encoding class and have tried to convert it each time with no success on this single record.

The SQL Collation is SQL_Latin1_General_CP1_CI_AS the MySQL collation is latin1_general_ci a sample of the code (in a foreach loop) is below:

foreach(var pgObj in PgObjList)
{
    //byte[] bytes = Encoding.Default.GetBytes(pgObj.Description);
    //pgObj.Description = Encoding.ASCII.GetString(bytes);

    byte[] utf8Bytes = Encoding.UTF8.GetBytes(pgObj.Description);
    byte[] isoBytes = Encoding.Convert(Encoding.ASCII, Encoding.UTF8, utf8Bytes);
    string uf8converted = Encoding.UTF8.GetString(isoBytes);

    string insertSQL = @"INSERT INTO `mainsite`.`sf_root_items`
                        (`ID`,
                        `LoweredName`,
                        `MenuName`,
                        `Title`,
                        `Description`,
                        `PageType`,
                        `ExternalUrl`
                        )
                        VALUES
                        ('" + pgObj.ID + @"',
                        '" + pgObj.LoweredName + @"',
                        '" + pgObj.MenuName + @"',
                        '" + pgObj.Title + @"',
                        '" + pgObj.Description + @"',
                        '" + pgObj.PageType + @"',
                        '" + pgObj.ExternalUrl + @"'
                        );";
    string outputMsg;
    // more code here to execute the MySQL statement
}

The best result I got was converting to ASCII (the commented code) and that stored the text in what looked like Chinese characters. There was no exception but when I run it any other way I get an exception with this record.

Exception:

MySQL Exception on record#28/r/n
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'il vous plaît (RSVP)',
                                                '0',
             ' at line 15
       at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
       at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
       at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
       at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
       at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
       at SharepointImportDL.SharepointContentImport.GetSitefinityContent.addRootItems(List`1 PgObjList, String WPConnectionString) in C:\Users\Administrator\Source\Repos\TestBinaryWriter\Test Binary Writer\SharepointImportDL\SharepointContentImport\GetSitefinityContent.cs:line 986

Line 986 is the SQL execution: int output = cmd.ExecuteNonQuery();

It may also be worth noting that the string that I'm inserting is from a nvarchar column (MSSQL) and into a varchar (MySQL) column

Ironically, the string is a simple "Répondez s'il vous plaît (RSVP)" (I want to punch the pretentious person who had to use the French text) so it's not likely I'll encounter it again but clearly I need to handle this possibility.

Body:
Escape strings (eg, pgObj.Description) before building the SQL (string insertSQL).  Otherwise you get syntax error from things like

, 'Répondez s'il vous plaît (RSVP)',

Notice how there is a single quote inside of single quotes?  Also notice how the error pointed at the problem:

... syntax to use near 'il vous plaît (RSVP)',


问:
Why do we need to use `int main` and not `void main` in C++?
Why do we need to use int main and not void main in C++?

答:
As in C, because the process will give the OS an exit code.

You can either use

```<code>int main (int argc, char ** argv)
{
  return (0);
}
</code>```

or

```<code>int main (int argc, char ** argv)
{
  exit (0);
}
</code>```

This is at least in C89 IIRC.

OwnerDisplayName: kasperasky

Body:
As in C, because the process will give the OS an exit code.

You can either use

int main (int argc, char ** argv)
{
  return (0);
}

or

int main (int argc, char ** argv)
{
  exit (0);
}

This is at least in C89 IIRC.

OwnerDisplayName: Keltia


问:
get result of two query with one query - mysql
```<code>$sql ="select * from user limit 5";
</code>```

is there any way that i can get limited number of results but with total results without limit.

Basically i want result of below two queries in one single query.

```<code>query 1 : select count(*) from user
query 2 : select * from user LIMIT 5
</code>```

is that possible without any sub query?

答:
```<code>select *, '' as total from user limit 5
UNION
select *,count(*) as total from user group by id>0
</code>```

Body:
$sql ="select * from user limit 5";

is there any way that i can get limited number of results but with total results without limit.

Basically i want result of below two queries in one single query.

query 1 : select count(*) from user
query 2 : select * from user LIMIT 5

is that possible without any sub query?


问:
delete elements from a data frame w.r.t columns of another data frame
I have a data frame say df1 with MULTILEVEL INDEX:

```<code>       A     B     C      D
 0  0    0     1     2      3
         4     5     6      7
 1  2    8     9     10     11
    3    2     3     4      5
</code>```

and I have another data frame with 2 common columns in df2 also with MULTILEVEL INDEX

```<code>          X     B     C      Y
 0   0    0     0     7      3
     1    4     5     6      7
 1   2    8     2     3     11
     3    2     3     4      5
</code>```

I need to remove the rows from df1 where the values of column B and C are the same as in df2, so I should be getting something like this:

```<code>       A     B     C      D
  0  0    0     1     2      3
  0  2    8     9     10     11
</code>```

I have tried to do this by getting the index of the common elements and then remove them via a list, but they are all messed up and are in multi-level form.

答:
You can do this in a one liner using pandas.dataframe.iloc, numpy.where and numpy.logical_or like this: (I find it to be the simplest way)

```<code>df1 = df1.iloc[np.where(np.logical_or(df1['B']!=df2['B'],df1['C']!=df2['C']))]
</code>```

of course don't forget to:

```<code>import numpy as np
</code>```

output:

```<code>     A  B   C   D
0 0  0  1   2   3
1 2  8  9  10  11
</code>```

Hope this was helpful. If there are any questions or remarks please feel free to comment.

Body:
I have a data frame say df1 with MULTILEVEL INDEX:

       A     B     C      D
 0  0    0     1     2      3
         4     5     6      7
 1  2    8     9     10     11
    3    2     3     4      5

and I have another data frame with 2 common columns in df2 also with MULTILEVEL INDEX

          X     B     C      Y
 0   0    0     0     7      3
     1    4     5     6      7
 1   2    8     2     3     11
     3    2     3     4      5

I need to remove the rows from df1 where the values of column B and C are the same as in df2, so I should be getting something like this:

       A     B     C      D
  0  0    0     1     2      3
  0  2    8     9     10     11

I have tried to do this by getting the index of the common elements and then remove them via a list, but they are all messed up and are in multi-level form.

Body:
You can do this in a one liner using pandas.dataframe.iloc, numpy.where and numpy.logical_or like this: (I find it to be the simplest way)

df1 = df1.iloc[np.where(np.logical_or(df1['B']!=df2['B'],df1['C']!=df2['C']))]

of course don't forget to:

import numpy as np

output:

     A  B   C   D
0 0  0  1   2   3
1 2  8  9  10  11

Hope this was helpful. If there are any questions or remarks please feel free to comment.


问:
I am trying to use PIVOT to convert rows to columns. I only have numeric examples, but I need to PIVOT with varchar
Need to convert the following

```<code>Country , code , result
('IND','AC1','Completed'),
    ('IND','AC2','Completed'),
    ('IND','AC3','Completed'),
    ('SL','AC1','Status'),
    ('SL','AC2','ERROR'),
    ('AUS','AC3','Completed')
</code>```

into

```<code>Country , ac1 , ac2 , ac3
------------------------
ind , Completed , Completed , Completed
sl, Status ,Error
AUS, , ,Completed
</code>```

答:
Using conditional aggregation:

```<code>select
    Country
  , max(case when code = 'AC1' then result else '' end) as AC1
  , max(case when code = 'AC2' then result else '' end) as AC2
  , max(case when code = 'AC3' then result else '' end) as AC3
from countries
group by Country
</code>```

using pivot() in SQL Server:

```<code>select
    Country
  , coalesce(AC1,'') as AC1
  , coalesce(AC2,'') as AC2
  , coalesce(AC3,'') as AC3
from countries
pivot (max(result) for code in (AC1,AC2,AC3)) p
</code>```

rextester demo: http://rextester.com/ZTLYWY22412

returns (for both):

```<code>+---------+-----------+-----------+-----------+
| Country |    AC1    |    AC2    |    AC3    |
+---------+-----------+-----------+-----------+
| AUS     |           |           | Completed |
| IND     | Completed | Completed | Completed |
| SL      | Status    | ERROR     |           |
+---------+-----------+-----------+-----------+
</code>```

Body:
Need to convert the following

Country , code , result
('IND','AC1','Completed'),
    ('IND','AC2','Completed'),
    ('IND','AC3','Completed'),
    ('SL','AC1','Status'),
    ('SL','AC2','ERROR'),
    ('AUS','AC3','Completed')

into

Country , ac1 , ac2 , ac3
------------------------
ind , Completed , Completed , Completed
sl, Status ,Error
AUS, , ,Completed

Body:
Using conditional aggregation:

select
    Country
  , max(case when code = 'AC1' then result else '' end) as AC1
  , max(case when code = 'AC2' then result else '' end) as AC2
  , max(case when code = 'AC3' then result else '' end) as AC3
from countries
group by Country

using pivot() in SQL Server:

select
    Country
  , coalesce(AC1,'') as AC1
  , coalesce(AC2,'') as AC2
  , coalesce(AC3,'') as AC3
from countries
pivot (max(result) for code in (AC1,AC2,AC3)) p

rextester demo: http://rextester.com/ZTLYWY22412

returns (for both):

+---------+-----------+-----------+-----------+
| Country |    AC1    |    AC2    |    AC3    |
+---------+-----------+-----------+-----------+
| AUS     |           |           | Completed |
| IND     | Completed | Completed | Completed |
| SL      | Status    | ERROR     |           |
+---------+-----------+-----------+-----------+


问:
Getting error while trying to use paramMap for getting route parameters
```<code>export class HeroDetailComponent {
    heroes;
    constructor(private route: ActivatedRoute, private router: Router, private hs : HeroService){
    }
    ngOnInit(){
        this.route.paramMap
            .switchMap((params : ParamMap) =>
                this.hs.getHeroes(params.get('id')))
            .subscribe((heroes) => {
                console.log("checking for heroes n subscribe",heroes);
                this.heroes = heroes})
    }

}
</code>```

Getting following error

paramMap doesn't exist on type 'ActivatedRoute'

答:
not too sure if this will help but you may want to try following:

delete the node_modules folder in your project

in your package.json file, check that your @angular/router dependency is of angular 4 version (ie 4.0.0 and up)

make sure your typescript version is at least 2.1.6 in both "dependencies" and "devDependencies" in your package.json (some versions of typescript and up breaks rxjs. i'm not too sure at which version and up that is. to be on the safe side, you may want to just update your rxjs to the latest version as well)

finally npm install

hopefully this works for you. i had the same issue and if i never remember wrongly, i did the above and ParamMap exist after.

Body:
export class HeroDetailComponent {
    heroes;
    constructor(private route: ActivatedRoute, private router: Router, private hs : HeroService){
    }
    ngOnInit(){
        this.route.paramMap
            .switchMap((params : ParamMap) =>
                this.hs.getHeroes(params.get('id')))
            .subscribe((heroes) => {
                console.log("checking for heroes n subscribe",heroes);
                this.heroes = heroes})
    }

}

Getting following error

paramMap doesn't exist on type 'ActivatedRoute'


答: This is a common problem, and as far as I know it just isn't possible.. Stick with two queries, it's fast and clear.</p>

Title: get result of two query with one query - mysql


问:
IOS/Objective-C: Change tint of an image view
I would like to change the color of an image view when the user touches it.  I don't need it to change a great deal.  However, I would like it to change to a shade of blue.  I found the following code to change the gradient but it is not having any effect.  I don't need a gradient, actually, only a tint.  Would appreciate any suggestions.</p>

```<code> UIView *snapshot = [[UIImageView alloc] initWithImage:image];
        snapshot.layer.masksToBounds = NO;
          CAGradientLayer *gradient = [CAGradientLayer layer];

        gradient.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor blackColor].CGColor];

        [snapshot.layer insertSublayer:gradient atIndex:0];
</code>```

答:
An easy and non-intrusive way is to add a translucent overlay to your image view. This can then be shown and hidden as the button is pressed and released.</p>

```<code>- (void)indicatedImageViewPressed:(UIImageView *)imageView on:(BOOL)on {
    UIView *overlay = [imageView viewWithTag:1]; // See if already created
    if (overlay == nil) {
        overlay = [[UIView alloc] initWithFrame:imageView.bounds];
        overlay.tag = 1; // Mark view to find it next time
        overlay.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:0.3]; // Your color overlay goes here
        [imageView addSubview:overlay];
    }
    overlay.hidden = !on;
}
</code>```

Body:
I would like to change the color of an image view when the user touches it.  I don't need it to change a great deal.  However, I would like it to change to a shade of blue.  I found the following code to change the gradient but it is not having any effect.  I don't need a gradient, actually, only a tint.  Would appreciate any suggestions.

 UIView *snapshot = [[UIImageView alloc] initWithImage:image];
        snapshot.layer.masksToBounds = NO;
          CAGradientLayer *gradient = [CAGradientLayer layer];

        gradient.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor blackColor].CGColor];

        [snapshot.layer insertSublayer:gradient atIndex:0];

Body:
An easy and non-intrusive way is to add a translucent overlay to your image view. This can then be shown and hidden as the button is pressed and released.

- (void)indicatedImageViewPressed:(UIImageView *)imageView on:(BOOL)on {
    UIView *overlay = [imageView viewWithTag:1]; // See if already created
    if (overlay == nil) {
        overlay = [[UIView alloc] initWithFrame:imageView.bounds];
        overlay.tag = 1; // Mark view to find it next time
        overlay.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:1.0 alpha:0.3]; // Your color overlay goes here
        [imageView addSubview:overlay];
    }
    overlay.hidden = !on;
}


问:
Cassandra policies configuration with CassandraAutoConfiguration
When using CassandraAutoConfiguration how the yml configuration should look like to configure  Class<? extends ...> fields e.g. reconnectionPolicy: com.datastax.driver.core.policies.ConstantReconnectionPolicy
with delayMs=3000

答:
So it seems providing a ClusterBuilderCustomizer with custom properties is the only option.</p>

```<code>  @Bean
public ClusterBuilderCustomizer clusterBuilderCustomizer(CassandraBaseProperties properties) {
    return builder -> builder.withReconnectionPolicy(
            new ConstantReconnectionPolicy(properties.getReconnectionPolicyConstantDelayMs()));
}
</code>```

Body:
So it seems providing a ClusterBuilderCustomizer with custom properties is the only option.

  @Bean
public ClusterBuilderCustomizer clusterBuilderCustomizer(CassandraBaseProperties properties) {
    return builder -> builder.withReconnectionPolicy(
            new ConstantReconnectionPolicy(properties.getReconnectionPolicyConstantDelayMs()));
}


问:
Is the following algorithm lock-free?
In my understanding, an algorithm is lock free if some thread always makes progress.

Now isn't this condition met by the following example (using locks):

Thread 1: using lock1 for critical section

Thread 2: using lock1 for critical section

Thread 3: some call independent of lock1 and the other two threads in general

答:
What you describe certainly isn't "lock-free" in any meaningful sense. Thread 1 and 2 are dependent on the same shared resource (a critical section, enforced by "lock1"), so if one of them acquires that lock and then gets suspended, then the other thread will deadlock waiting on it.

Sure, Thread 3 will continue on unabated, but so will Thread A, B, and C (i.e., threads that have nothing to do with your program). That seems to be irrelevant when looking at the algorithm as a whole, which presumably consists of all three threads.

Essentially, the problem with your definition of "lock-free" is that it isn't precise enough. You say that an algorithm is lock-free "if some thread always makes progress", but you fail to look at the algorithm as a whole.

Thread 3 is trivially lock-free (because it makes progress on its own, without the assistance of any other threads), but your overall algorithm is not.

A better way to assess whether an algorithm is lock-free is asking yourself: if a single thread gets suspended, will this prevent the other threads from making progress as a group? In this case, yes. If Thread 1 or Thread 2 acquires the lock and then gets suspended, this will prevent the other thread from executing, and presumably these other threads are doing work that is important to your algorithm.

I recommend Jeff Preshing's blog post, "An Introduction to Lock-Free Programming". Here's a handy flow chart from that blog post:

 Yes -> Do the threads access shared memory? -> Yes -> Can the threads block each other? -> No -> It's lock-free programming!">

Title: Is the following algorithm lock-free?


问:
Combining templates and type safety
Let's say I have several functions defined like this:

```<code>template <typename T>
inline void read<bool>(T **data) {
    //some code
}

template <typename T>
inline void read<double>(T **data) {
    //some other code
}

template <typename T>
inline void read<int>(T **data) {
    //also different code
}
</code>```

Now, I create another function defined like this:

```<code>template<typename T>
inline void readMultiple(T **data, int counter) {
    for (int i = 0; i < counter, ++i) {
       read<T>(data);
    }
}
</code>```

(1)That would call the appropriate read<T>(T **data) implementation based on the type T, right?

(2)If I were to specify a type that is not one of the three above, I'd get a compilation error, since that function is not defined, right?

(3)Also, can I make this call:

```<code>double **d;
read<double>(d);
</code>```

to ensure that I called the implementation for double?

I know I'd get the same result without the <double> part, but this way I'm ensuring that double is passed to the function, where as doing it without <double> would allow for d to be a int or a bool and the code would still compile, silently introducing an error.

答:
(1)That would call the appropriate read<T>(T **data) implementation based on the type T, right?

Yes, assuming the specializations are visible at the point where read<T>(data) is encountered.

(2)If I were to specify a type that is not one of the three above, I'd get a compilation error, since that function is not defined, right?

You haven't provided your declaration of the template read() function, so this can't be answered.  Assuming that you have declared it like template <typename T> void read(T**); and have not defined it anywhere then yes, you would get a link-time error when the linker is unable to find an implementation of the requested specialization.

(3)Also, can I make this call:

```<code>double **d;
read<double>(d);
</code>```

to ensure that I called the implementation for double?

You can, though <double> is superfluous and will be inferred.

... silently introducing an error.

If the thing you're passing is a bool** then it would not be an error to use the bool specialization.  I don't really see any benefit from explicitly providing the template arguments.  If bool** is the wrong type then presumably you would be getting errors somewhere else, anyway.

I guess it depends on what you mean by "silently introducing an error."  It's not clear what kind of error you're trying to prevent.  I can come up with a contrived example, but contrived examples rarely represent real-world dangers.

Two side notes:

The syntax for your specializations is incorrect.  It should be template <> inline void read<bool>(bool **data) { /* ... */ } for example.

There's no need for templates here at all, you can just have three function overloads.  Having an undefined template function with explicit specializations is an anti-pattern; overloads are the recommended way to implement the same thing.

Title: Combining templates and type safety

Body:
Let's say I have several functions defined like this:

template <typename T>
inline void read<bool>(T **data) {
    //some code
}

template <typename T>
inline void read<double>(T **data) {
    //some other code
}

template <typename T>
inline void read<int>(T **data) {
    //also different code
}

Now, I create another function defined like this:

template<typename T>
inline void readMultiple(T **data, int counter) {
    for (int i = 0; i < counter, ++i) {
       read<T>(data);
    }
}

(1)That would call the appropriate read<T>(T **data) implementation based on the type T, right?

(2)If I were to specify a type that is not one of the three above, I'd get a compilation error, since that function is not defined, right?

(3)Also, can I make this call:

double **d;
read<double>(d);

to ensure that I called the implementation for double?

I know I'd get the same result without the <double> part, but this way I'm ensuring that double is passed to the function, where as doing it without <double> would allow for d to be a int or a bool and the code would still compile, silently introducing an error.

Body:
(1)That would call the appropriate read<T>(T **data) implementation based on the type T, right?

Yes, assuming the specializations are visible at the point where read<T>(data) is encountered.

(2)If I were to specify a type that is not one of the three above, I'd get a compilation error, since that function is not defined, right?

You haven't provided your declaration of the template read() function, so this can't be answered.  Assuming that you have declared it like template <typename T> void read(T**); and have not defined it anywhere then yes, you would get a link-time error when the linker is unable to find an implementation of the requested specialization.

(3)Also, can I make this call:

double **d;
read<double>(d);

to ensure that I called the implementation for double?

You can, though <double> is superfluous and will be inferred.

... silently introducing an error.

If the thing you're passing is a bool** then it would not be an error to use the bool specialization.  I don't really see any benefit from explicitly providing the template arguments.  If bool** is the wrong type then presumably you would be getting errors somewhere else, anyway.

I guess it depends on what you mean by "silently introducing an error."  It's not clear what kind of error you're trying to prevent.  I can come up with a contrived example, but contrived examples rarely represent real-world dangers.

Two side notes:

The syntax for your specializations is incorrect.  It should be template <> inline void read<bool>(bool **data) { /* ... */ } for example.

There's no need for templates here at all, you can just have three function overloads.  Having an undefined template function with explicit specializations is an anti-pattern; overloads are the recommended way to implement the same thing.


问:
ColdFusion with IIS Forms Based Authentication
I'm trying to setup Forms Based Authentication in IIS 7.5 with ColdFusion 10. It's somewhat working but not prompting for ColdFusion pages. Yes, I did enable the Integrated Pipeline to force auth on all files. Then, I disabled auth on the two ColdFusion Virtual Directories. Not doing so caused a redirect to /jakarta/isapi_redirect.dll instead of the real/calling page.

So the interesting thing is that ColdFusion files (.cfm .cfc) seem to get past the authentication because they are processed by the un-authenticated Virtual Directories.?. (even though the requested page is still the called page..)

Any thoughts would be appreciated. Thanks!

答:
I found that the FormAuthentication iis module was not being called for isapi_redirect.dll(jakarta pages) probably because of the precondition preCondition="managedHandler" that's default on FormAuthentication module.
Adding

```<code><modules runAllManagedModulesForAllRequests="true" >;
</code>```

in web.config allowed things to work as intended.

Enabling Trace Logging for Failed Requests were indispensable in figuring this out.  This was with win2016/cf2016/iis10.

Body:
I found that the FormAuthentication iis module was not being called for isapi_redirect.dll(jakarta pages) probably because of the precondition preCondition="managedHandler" that's default on FormAuthentication module.
Adding

<modules runAllManagedModulesForAllRequests="true" >;

in web.config allowed things to work as intended.

Enabling Trace Logging for Failed Requests were indispensable in figuring this out.  This was with win2016/cf2016/iis10.


问:
How to separate one column to multiple column (complex column)
I am trying to separate column "Grade" to multiple columns according to their subject and grade

```<code>    grade<-read.csv("https://raw.githubusercontent.com/tuyenhavan/Statistics/Dataset/High_school_Grade.csv",sep=";")

# Rename the column names

    names(grade)<-c("Student_ID","Name","Venue","Grade")

    head(grade)

    # Separate `Grade` into `subject` variables and coresponding `Grade`columns
    library(tidyverse)

    df<- grade %>% separate(Grade,paste("V",1:7,sep="_"),sep=":")

    head(df)

    # It still is not separating `subject ` and `grade` independently

    # Here is what I want it to look like

    new_df<-df[c(1:5),c(1:4)]

    new_df<-data.frame(new_df, V2=c(1:5)) # the same for V2,4,5,6,,7 to separate subject and grade

    new_df
</code>```

I am trying to use dplyr and stringr, but could not produce the result as I expected

答:
In my solution below, I have used functions from the tidyverse and rebus packages. The rebus package builds regular expressions piece by piece using human readable code.

```<code> library(tidyverse)
 library(rebus)
 grade<-read.csv("https://raw.githubusercontent.com/tuyenhavan/Statistics/Dataset/High_school_Grade.csv",
                 sep = ";", stringsAsFactors = FALSE)

 grade_new <- grade %>%
   mutate(DIEM_THI2 = str_replace_all(DIEM_THI, pattern = ":" %R% one_or_more(SPC), "-")) %>%
   separate_rows(DIEM_THI2, sep = one_or_more(SPC)) %>%
   separate(DIEM_THI2, c("SUBJECT", "GRADE"), sep = "-") %>%
   spread(SUBJECT,GRADE)
</code>```

The resulting dataframe looks like the following:

```<code>head(grade_new[,5:12])
#   Biology Chemitry English Geography History Literature Math Physics
# 1    6.00     6.00    <NA>      <NA>    <NA>       7.50 4.25    6.80
# 2    5.80     6.00    <NA>      <NA>    <NA>       6.00 5.75    <NA>
# 3    <NA>     <NA>    <NA>      8.00    4.50       7.75 2.25    <NA>
# 4    <NA>     <NA>    <NA>      7.25    7.50       7.75 3.25    <NA>
# 5    <NA>     <NA>    <NA>      7.75    4.50       8.25 1.75    <NA>
# 6    <NA>     6.60    6.78      <NA>    <NA>       7.00 8.75    8.40
</code>```

The code can be understood as follows:

All colon+space substrings are replaced with hyphens. i.e. "Math: 4.25 Literature: 7.50" becomes "Math-4.25 Literature-7.50". This is done using the str_replace_all function. Lets call the new variable DIEM_THI2.

The separate_rows function splits the space-separated column, DIEM_THI2 into separate rows  i.e. "Math-4.25" and "Literature-7.50" span over two different rows.

The DIEM_THI2 column is separated into two columns, i.e. SUBJECT and GRADE where the former contains values like "Math", "Literature" and the latter contains values like "4.25" and "7.50".

The key-value pair or SUBJECT-GRADE pair are spread across multiple columns.

Body:
I am trying to separate column "Grade" to multiple columns according to their subject and grade

    grade<-read.csv("https://raw.githubusercontent.com/tuyenhavan/Statistics/Dataset/High_school_Grade.csv",sep=";")

# Rename the column names

    names(grade)<-c("Student_ID","Name","Venue","Grade")

    head(grade)

    # Separate `Grade` into `subject` variables and coresponding `Grade`columns
    library(tidyverse)

    df<- grade %>% separate(Grade,paste("V",1:7,sep="_"),sep=":")

    head(df)

    # It still is not separating `subject ` and `grade` independently

    # Here is what I want it to look like

    new_df<-df[c(1:5),c(1:4)]

    new_df<-data.frame(new_df, V2=c(1:5)) # the same for V2,4,5,6,,7 to separate subject and grade

    new_df

I am trying to use dplyr and stringr, but could not produce the result as I expected

Body:
In my solution below, I have used functions from the tidyverse and rebus packages. The rebus package builds regular expressions piece by piece using human readable code.

 library(tidyverse)
 library(rebus)
 grade<-read.csv("https://raw.githubusercontent.com/tuyenhavan/Statistics/Dataset/High_school_Grade.csv",
                 sep = ";", stringsAsFactors = FALSE)

 grade_new <- grade %>%
   mutate(DIEM_THI2 = str_replace_all(DIEM_THI, pattern = ":" %R% one_or_more(SPC), "-")) %>%
   separate_rows(DIEM_THI2, sep = one_or_more(SPC)) %>%
   separate(DIEM_THI2, c("SUBJECT", "GRADE"), sep = "-") %>%
   spread(SUBJECT,GRADE)

The resulting dataframe looks like the following:

head(grade_new[,5:12])
#   Biology Chemitry English Geography History Literature Math Physics
# 1    6.00     6.00    <NA>      <NA>    <NA>       7.50 4.25    6.80
# 2    5.80     6.00    <NA>      <NA>    <NA>       6.00 5.75    <NA>
# 3    <NA>     <NA>    <NA>      8.00    4.50       7.75 2.25    <NA>
# 4    <NA>     <NA>    <NA>      7.25    7.50       7.75 3.25    <NA>
# 5    <NA>     <NA>    <NA>      7.75    4.50       8.25 1.75    <NA>
# 6    <NA>     6.60    6.78      <NA>    <NA>       7.00 8.75    8.40

The code can be understood as follows:

All colon+space substrings are replaced with hyphens. i.e. "Math: 4.25 Literature: 7.50" becomes "Math-4.25 Literature-7.50". This is done using the str_replace_all function. Lets call the new variable DIEM_THI2.

The separate_rows function splits the space-separated column, DIEM_THI2 into separate rows  i.e. "Math-4.25" and "Literature-7.50" span over two different rows.

The DIEM_THI2 column is separated into two columns, i.e. SUBJECT and GRADE where the former contains values like "Math", "Literature" and the latter contains values like "4.25" and "7.50".

The key-value pair or SUBJECT-GRADE pair are spread across multiple columns.


问:
is there an easy way to add/delete/replace classes in asp.net cssclass
I have some elements on the screen that I want to dynamically change back and forth between CSS classes "active" and "inactive". So okay, in principle I could write:

```<code>if active then
  foo.cssclass="active"
else
  foo.cssclass="inactive"
end if
</code>```

But these elements have other classes on them too. I think clean coding principles would call for the function that sets active/inactive to not have to know what other classes are presently attached to that object. So what I really want is something like:

```<code>foo.cssclass.remove("inactive").add("active")
</code>```

Which is a nice fantasy but CSSCLASS is a string. Is there an easy way to do this?

I suppose it would not be a tremendously challenging task to write a function that manipulates the string. So ... is there some clean, easy way to do this? Or do I have to write my own function?

答:
Not very elegant but it should work:

```<code>foo.CssClass = foo.CssClass.Replace("inactive","").Trim() + " active";
</code>```

or viceversa

```<code>foo.CssClass = foo.CssClass.Replace("active","").Trim() + " inactive";
</code>```

Body:
I have some elements on the screen that I want to dynamically change back and forth between CSS classes "active" and "inactive". So okay, in principle I could write:

if active then
  foo.cssclass="active"
else
  foo.cssclass="inactive"
end if

But these elements have other classes on them too. I think clean coding principles would call for the function that sets active/inactive to not have to know what other classes are presently attached to that object. So what I really want is something like:

foo.cssclass.remove("inactive").add("active")

Which is a nice fantasy but CSSCLASS is a string. Is there an easy way to do this?

I suppose it would not be a tremendously challenging task to write a function that manipulates the string. So ... is there some clean, easy way to do this? Or do I have to write my own function?

Body:
Not very elegant but it should work:

foo.CssClass = foo.CssClass.Replace("inactive","").Trim() + " active";

or viceversa

foo.CssClass = foo.CssClass.Replace("active","").Trim() + " inactive";


问:
Simple mouseover effect on NSButton
I am creating a custom NSButtonCell for a custom rendering.

Now, I want to have different aspect depending if the mouse is over the button or not.  How can I get this information?

Thanks and regards,

答:
Swift 3:

Create the button with code or just use it's @IBOutlet.
Then define the button's tracking area for mouse over (hover):

```<code>let area = NSTrackingArea.init(rect: yourButtonName.bounds,
                               options: [.mouseEnteredAndExited, .activeAlways],
                               owner: self,
                               userInfo: nil)
yourButtonName.addTrackingArea(area)
</code>```

Then override mouseEntered and mouseExited, set whatever you want to change (button color, button image, button text,..) in these functions:

```<code>override func mouseEntered(with event: NSEvent) {
    print("Entered: \(event)")
}

override func mouseExited(with event: NSEvent) {
    print("Exited: \(event)")
}
</code>```

If you have multiple buttons (with tracking area added for each) and you need to identify which button triggered the mouseEntered event, you can add some userInfo information for this purpose, so instead of:

```<code>userInfo: nil
</code>```

Add your custom button name in userInfo for each button, for example:

```<code>userInfo: ["btnName": "yourButtonName"]
</code>```

Then you can write a switch-case or if statements in your mouseEntered and mouseExited functions like this:

```<code>override func mouseEntered(with event: NSEvent) {
        // Identify which button triggered the mouseEntered event
        if let buttonName = event.trackingArea?.userInfo?.values.first as? String {
            switch (buttonName) {
            case "yourButtonName":
                //do whatever you want for this button..
            case "anotherButtonName":
                //do whatever you want for this button..
            default:
                print("The given button name: \"\(buttonName)\" is unknown!")
            }
        }
    }
</code>```

Title: Simple mouseover effect on NSButton

Body:
Swift 3:

Create the button with code or just use it's @IBOutlet.
Then define the button's tracking area for mouse over (hover):

let area = NSTrackingArea.init(rect: yourButtonName.bounds,
                               options: [.mouseEnteredAndExited, .activeAlways],
                               owner: self,
                               userInfo: nil)
yourButtonName.addTrackingArea(area)

Then override mouseEntered and mouseExited, set whatever you want to change (button color, button image, button text,..) in these functions:

override func mouseEntered(with event: NSEvent) {
    print("Entered: \(event)")
}

override func mouseExited(with event: NSEvent) {
    print("Exited: \(event)")
}

If you have multiple buttons (with tracking area added for each) and you need to identify which button triggered the mouseEntered event, you can add some userInfo information for this purpose, so instead of:

userInfo: nil

Add your custom button name in userInfo for each button, for example:

userInfo: ["btnName": "yourButtonName"]

Then you can write a switch-case or if statements in your mouseEntered and mouseExited functions like this:

override func mouseEntered(with event: NSEvent) {
        // Identify which button triggered the mouseEntered event
        if let buttonName = event.trackingArea?.userInfo?.values.first as? String {
            switch (buttonName) {
            case "yourButtonName":
                //do whatever you want for this button..
            case "anotherButtonName":
                //do whatever you want for this button..
            default:
                print("The given button name: \"\(buttonName)\" is unknown!")
            }
        }
    }


问:
How to stop PHP Output error on a specific file (page) (JSON)
My friend gave me free hosting, and I am doing CRON job on his server. But he said, your CRON job is affecting my server. Just stop the output and everything will be fine.

This is my JSON code

```<code>$response = file_get_contents("https://api.themoviedb.org/3/movie/".$requestsDone."?api_key=522cec782xxxx6f6d1e0c834a");
if ($response != FALSE) {
$response = json_decode($response, true);
}
</code>```

So, i removed all echo lines. But, I still get this error echo'ed.

```<code>Warning: file_get_contents(https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
</code>```

I am opening Thousands of URL's, and some URL contain this line

{"status_code":34,"status_message":"The resource you requested could not be found."}

Just this line, nothing more.

So, the page is still opening, why it gives that error? How to stop that?

Or just anyway to stop PHP echoing the error on the page (just for this file, not for whole website).

答:
first check this condition if($content === FALSE) { } .

if still you get same problem use @ in front of the call to file_get_contents(): $content = @file_get_contents($site);

Body:
My friend gave me free hosting, and I am doing CRON job on his server. But he said, your CRON job is affecting my server. Just stop the output and everything will be fine.

This is my JSON code

$response = file_get_contents("https://api.themoviedb.org/3/movie/".$requestsDone."?api_key=522cec782xxxx6f6d1e0c834a");
if ($response != FALSE) {
$response = json_decode($response, true);
}

So, i removed all echo lines. But, I still get this error echo'ed.

Warning: file_get_contents(https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

I am opening Thousands of URL's, and some URL contain this line

{"status_code":34,"status_message":"The resource you requested could not be found."}

Just this line, nothing more.

So, the page is still opening, why it gives that error? How to stop that?

Or just anyway to stop PHP echoing the error on the page (just for this file, not for whole website).


问:
How to set the alignment of the chart in matplotlib.pyplot?
I have two numpy.ndarray and both have the same number of datas as follow :

```<code>data1 = [1,2,3,4,5,6,7,8,9]
data2 = [Nan, Nan, Nan, 14,15,16,17,18,19]
</code>```

When, I plot these data, the data1 occupies the whole width of the window. But since data2 has NaN, only the non-NaN data will be shown on the window and they are in the middle.

How can I set the matplotlib.pyplot so that they are aligned on the right side/edge of the window?

Hi, the screenshot1 is the actual situation. The screenshot 2 is what I want, i.e. the charts are right aligned.

答:
Maybe not plotting the data array, but a masked array in case of NaN's could help.

```<code>import numpy as np

data2_masked = np.ma.masked_array(data2, mask=np.isnan(data2)
</code>```

And then plot the masked array instead of the data2 array containing the nan values

Body:
I have two numpy.ndarray and both have the same number of datas as follow :

data1 = [1,2,3,4,5,6,7,8,9]
data2 = [Nan, Nan, Nan, 14,15,16,17,18,19]

When, I plot these data, the data1 occupies the whole width of the window. But since data2 has NaN, only the non-NaN data will be shown on the window and they are in the middle.

How can I set the matplotlib.pyplot so that they are aligned on the right side/edge of the window?

Hi, the screenshot1 is the actual situation. The screenshot 2 is what I want, i.e. the charts are right aligned.

Body:
Maybe not plotting the data array, but a masked array in case of NaN's could help.

import numpy as np

data2_masked = np.ma.masked_array(data2, mask=np.isnan(data2)

And then plot the masked array instead of the data2 array containing the nan values


问:
tab panel space
I have a bootstrap tab pane, im try to create two  details  are between some space , but its not working , you can understand it , look images
how can i fix this issue , please help me to fix it,
i need like this one

issue is like this

my code part
Html

```<code><div class="notification-group">
  <div class="col-lg-6 col-sm-6">

      <div class="btn-pref btn-group btn-group-justified btn-group-lg" role="group" aria-label="...">
          <div class="btn-group" role="group">
              <button type="button" id="stars" class="btn btn-primary" href="#tab1" data-toggle="tab">
                feed (10)
              </button>
          </div>
          <div class="btn-group" role="group">
              <button type="button" id="favorites" class="btn btn-default" href="#tab2" data-toggle="tab">

                Task (03)
              </button>
          </div>

      </div>

         <div class="well">

        <div class="tab-content">
          <div class="tab-pane fade in active" id="tab1">
            <h4>This is tab 12</h4>

          </div>

<div class="tab-pane fade in active" id="tab1">
  <h4>This is tab 12</h4>

</div>
     <div class="tab-pane fade in" id="tab2">
            <h4>This is tab 22</h4>
          </div>

        </div>

      </div>
      </div>
</div>
</code>```

css

```<code>.notification-group  .btn-group > .btn, .btn-group-vertical > .btn {
    position: relative;
    float: left;
}

.btn-group > .btn, .btn-group-vertical > .btn {
    position: relative;
    float: left;
}

.notification-group .btn-default {
  color: black;
    background-color: #ffffff;
    border-color: #ccc;
}

.notification-group .btn-primary {
    color: black;
    background-color:#e5e5e5;
    border-color: #d7d7d7;
}

.notification-group .well {
    min-height: 20px;
    padding: 19px; width: 382px;
    margin: 5px;
    background-color: #e5e5e5;
    border: 1px solid #e3e3e3;
    border-radius: 0px; margin-left: -5px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);

}

.notification-group  .tab-content {
    height: 28px;
    width: 100%;

}
</code>```

答:
You have applied .notification-group .well change the value of width as per your requirement. For example you can use width: 50%; as I have done in the following code.

```<code>.notification-group .well {
    min-height: 20px;
    padding: 19px; **width: 382px;** /* width: 50%; */
    margin: 5px;
    background-color: #e5e5e5;
    border: 1px solid #e3e3e3;
    border-radius: 0px; margin-left: -5px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
}
</code>```

Title: tab panel space

Body:
I have a bootstrap tab pane, im try to create two  details  are between some space , but its not working , you can understand it , look images
how can i fix this issue , please help me to fix it,
i need like this one

issue is like this

my code part
Html

              <button type="button" id="stars" class="btn btn-primary" href="#tab1" data-toggle="tab">
                feed (10)
              </button>

              <button type="button" id="favorites" class="btn btn-default" href="#tab2" data-toggle="tab">

                Task (03)
              </button>

This is tab 12

This is tab 12

This is tab 22

css

.notification-group  .btn-group > .btn, .btn-group-vertical > .btn {
    position: relative;
    float: left;
}

.btn-group > .btn, .btn-group-vertical > .btn {
    position: relative;
    float: left;
}

.notification-group .btn-default {
  color: black;
    background-color: #ffffff;
    border-color: #ccc;
}

.notification-group .btn-primary {
    color: black;
    background-color:#e5e5e5;
    border-color: #d7d7d7;
}

.notification-group .well {
    min-height: 20px;
    padding: 19px; width: 382px;
    margin: 5px;
    background-color: #e5e5e5;
    border: 1px solid #e3e3e3;
    border-radius: 0px; margin-left: -5px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);

}

.notification-group  .tab-content {
    height: 28px;
    width: 100%;

}

Body:
You have applied .notification-group .well change the value of width as per your requirement. For example you can use width: 50%; as I have done in the following code.

.notification-group .well {
    min-height: 20px;
    padding: 19px; **width: 382px;** /* width: 50%; */
    margin: 5px;
    background-color: #e5e5e5;
    border: 1px solid #e3e3e3;
    border-radius: 0px; margin-left: -5px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);
}


问:
Naming of parse string and assign value
Sometimes I have this kind of code, Any advise to improve the readability
of result[0], result[1]...event the naming of result</p>

```<code>var productData = "Egg 1.24 1.36";
var result = productData..Split(new char[] { ' ' });

var product = new
{
Name = result[0],
BuyPrice = result[1],
SellPrice = result[2],
};
</code>```

答:
That's probably overkill, but you could use an extension method based on C#
 7 and ValueTuple to name your values right away. For instance:

```<code>public static class StringExtensions
{
    public static ValueTuple<string, string, string> Split(this string input, string delimiter)
    {
        var values = input.Split(new[] { delimiter }, StringSplitOptions.None);

        return (values[0], values[1], values[2]);
    }
}
</code>```

Then use it like that:

```<code>var (name, buyPrice, sellPrice) = productData.Split(" ");

Console.WriteLine(name);
</code>```

Edit: Actually, there's a smarter way. Just write an extension method to deconstruct an array:

```<code>public static class ArrayExtensions
{
    public static void Deconstruct<T>(this T[] values, out T item1, out T item2, out T item3)
    {
        item1 = values[0];
        item2 = values[1];
        item3 = values[2];
    }
}
</code>```

Now you can just use the original string.Split and assign the values like the first example:

```<code>var (name, buyPrice, sellPrice) = productData.Split(new[] { " " }, StringSplitOptions.None);
</code>```

Title: Naming of parse string and assign value

Body:
Sometimes I have this kind of code, Any advise to improve the readability
of result[0], result[1]...event the naming of result

var productData = "Egg 1.24 1.36";
var result = productData..Split(new char[] { ' ' });

var product = new
{
Name = result[0],
BuyPrice = result[1],
SellPrice = result[2],
};

Body:
That's probably overkill, but you could use an extension method based on C#
 7 and ValueTuple to name your values right away. For instance:

public static class StringExtensions
{
    public static ValueTuple<string, string, string> Split(this string input, string delimiter)
    {
        var values = input.Split(new[] { delimiter }, StringSplitOptions.None);

        return (values[0], values[1], values[2]);
    }
}

Then use it like that:

var (name, buyPrice, sellPrice) = productData.Split(" ");

Console.WriteLine(name);

Edit: Actually, there's a smarter way. Just write an extension method to deconstruct an array:

public static class ArrayExtensions
{
    public static void Deconstruct<T>(this T[] values, out T item1, out T item2, out T item3)
    {
        item1 = values[0];
        item2 = values[1];
        item3 = values[2];
    }
}

Now you can just use the original string.Split and assign the values like the first example:

var (name, buyPrice, sellPrice) = productData.Split(new[] { " " }, StringSplitOptions.None);


问:
Item position in list
I have this dictionary:

```<code>db= {'www.baurom.ro':
                     {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                     },
    'slbz2':
            {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    }
</code>```

And a list:

```<code>lista=['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']
</code>```

What am i doing now is this:

```<code>for x in lista:
     if x in db:
        db[x][0][lista.index(x)]+=1
</code>```

In other words i want to count how many times each site appears in the list and on which position. This works but in the given example it will return something like:

```<code>{0: [7, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</code>```

while i would want it to be:

```<code>{0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]
</code>```

How can i achieve this? I can use a variable, initiate it with var=0 and then +=1 and use it as an artificial index but is there a more "pythonic" way of doing it?

答:
If I rightly understand your question, you already have db dictionary and you're seeking enumerate operator.

And your code will be like below:

```<code>for index, element in enumerate(lista):
    if element in db:
        db[element][0][index] = 1
</code>```

Title: Item position in list

Body:
I have this dictionary:

db= {'www.baurom.ro':
                     {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
                     },
    'slbz2':
            {0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
             1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    }

And a list:

lista=['www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.baurom.ro', 'www.listafirme.ro', 'www.romanian-companies.eu', 'www.risco.ro']

What am i doing now is this:

for x in lista:
     if x in db:
        db[x][0][lista.index(x)]+=1

In other words i want to count how many times each site appears in the list and on which position. This works but in the given example it will return something like:

{0: [7, 0, 0, 0, 0, 0, 0, 0, 0, 0]

while i would want it to be:

{0: [1, 1, 1, 1, 1, 1, 1, 0, 0, 0]

How can i achieve this? I can use a variable, initiate it with var=0 and then +=1 and use it as an artificial index but is there a more "pythonic" way of doing it?

Body:
If I rightly understand your question, you already have db dictionary and you're seeking enumerate operator.

And your code will be like below:

for index, element in enumerate(lista):
    if element in db:
        db[element][0][index] = 1


问:
get result of two query with one query - mysql
```<code>$sql ="select * from user limit 5";
</code>```

is there any way that i can get limited number of results but with total results without limit.

Basically i want result of below two queries in one single query.

```<code>query 1 : select count(*) from user
query 2 : select * from user LIMIT 5
</code>```

is that possible without any sub query?

答:
single query not possible if without join or union, however, you can try something like</p>

```<code>select sql_calc_found_rows * from user limit 5;
select found_rows();  <-- total from first query
</code>```

Body:
$sql ="select * from user limit 5";

is there any way that i can get limited number of results but with total results without limit.

Basically i want result of below two queries in one single query.

query 1 : select count(*) from user
query 2 : select * from user LIMIT 5

is that possible without any sub query?

Body:
single query not possible if without join or union, however, you can try something like

select sql_calc_found_rows * from user limit 5;
select found_rows();  <-- total from first query


问:
How can I tell the filetype of images without extension? How do they work?
I am dealing with images on the web that come without a file extension, like this:

```<code>https://static1.squarespace.com/static/52a74d9ae4b0253945d2aee9/t/52ed63b1e4b04368c021b921/1463088116168/?format=500w
</code>```

Images like these can be found, e.g., on websites made with squarespace, like this demo: https://bedford-demo.squarespace.com/

I'm trying to download these images and store them on my server, using PHP. But how can I find out the actual URL of those images? How does this work? And how can I tell the filetype of this image? What is this sorcery?

Any hints are appreciated!

答:
You can get the mime type of the file with getimagesize:

```<code><?php
$size = getimagesize("https://static1.squarespace.com/static/52a74d9ae4b0253945d2aee9".
            "/t/52ed63b1e4b04368c021b921/1463088116168/?format=500w");
print_r($size["mime"]);
?>
</code>```

Prints:

```<code>image/jpeg
</code>```

Body:
I am dealing with images on the web that come without a file extension, like this:

https://static1.squarespace.com/static/52a74d9ae4b0253945d2aee9/t/52ed63b1e4b04368c021b921/1463088116168/?format=500w

Images like these can be found, e.g., on websites made with squarespace, like this demo: https://bedford-demo.squarespace.com/

I'm trying to download these images and store them on my server, using PHP. But how can I find out the actual URL of those images? How does this work? And how can I tell the filetype of this image? What is this sorcery?

Any hints are appreciated!

Body:
You can get the mime type of the file with getimagesize:

<?php
$size = getimagesize("https://static1.squarespace.com/static/52a74d9ae4b0253945d2aee9".
            "/t/52ed63b1e4b04368c021b921/1463088116168/?format=500w");
print_r($size["mime"]);
?>

Prints:

image/jpeg


问:
Select count, inner joins and where statements
This is erp.orders:

```<code>userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01
</code>```

This is prod.referral_order_delivered

```<code>user_id
1
2
</code>```

This request :

```<code>select distinct erp.orders."userId", count(erp.orders."userId")
from erp.orders
inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
group by erp.orders."userId"
</code>```

will give me this result:

```<code>userId  count
1       2
2       1
</code>```

This is not the result I want. Among the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered, I want to count how many times they appear in the table erp.orders IN TOTAL.
In my current request, I only count from 2017-06-07 to 2017-07-07.

The result I want is :

```<code>userId  count
1       2
2       4
</code>```

See how userId 3 and 4 are excluded. This is really important. Could you modify my request, please?

答:
When you use inner join you are discarding info that you need in the "WHERE" clause later on. Because it creates a temporal resulting table in which you omit the entries here:

```<code>where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
</code>```

So what you need to do is using semi-join instead as follows:

```<code>SELECT DISTINCT erp.orders."userId", COUNT(erp.orders."userId")
FROM erp.orders
WHERE erp.orders."userId" IN (
    SELECT erp.orders."userId"
    FROM erp.orders, prod.referral_order_delivered
    WHERE erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
    AND erp.orders."paidAt"::date >= '2017-06-07'
    AND erp.orders."paidAt"::date <= '2017-07-07'
);
GROUP BY erp.orders."userId"
</code>```

hope it helps!

Body:
This is erp.orders:

userId  paidAt
1       2017-06-30
1       2017-06-18
2       2017-06-07
4       2017-06-07
3       2017-01-01
2       2017-01-01
2       2017-01-01
2       2017-01-01

This is prod.referral_order_delivered

user_id
1
2

This request :

select distinct erp.orders."userId", count(erp.orders."userId")
from erp.orders
inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'
group by erp.orders."userId"

will give me this result:

userId  count
1       2
2       1

This is not the result I want. Among the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered, I want to count how many times they appear in the table erp.orders IN TOTAL.
In my current request, I only count from 2017-06-07 to 2017-07-07.

The result I want is :

userId  count
1       2
2       4

See how userId 3 and 4 are excluded. This is really important. Could you modify my request, please?

Body:
When you use inner join you are discarding info that you need in the "WHERE" clause later on. Because it creates a temporal resulting table in which you omit the entries here:

where
   erp.orders."paidAt"::date >= '2017-06-07'
   and erp.orders."paidAt"::date <= '2017-07-07'

So what you need to do is using semi-join instead as follows:

SELECT DISTINCT erp.orders."userId", COUNT(erp.orders."userId")
FROM erp.orders
WHERE erp.orders."userId" IN (
    SELECT erp.orders."userId"
    FROM erp.orders, prod.referral_order_delivered
    WHERE erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
    AND erp.orders."paidAt"::date >= '2017-06-07'
    AND erp.orders."paidAt"::date <= '2017-07-07'
);
GROUP BY erp.orders."userId"

hope it helps!


问:
How to create a selector with a vector assets over a circle?
I want to implement a toggle button that can pass from "start" to "pause" with the following design:

I put a ToggleButton, and I tried to use the following selector, but it does not work. In fact, only the circled background is displayed, but not the vector images (xml files) of the play and pause icons...

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_pressed="true">
    <layer-list>
        <item android:drawable="@drawable/ic_pause_black_24dp">
        </item>

        <item>
            <shape android:shape="oval">
                <solid android:color="@color/colorAccent"/>
            </shape>
        </item>
    </layer-list>
</item>

<item android:state_pressed="false">
    <layer-list>
        <item android:drawable="@drawable/ic_play_arrow_black_24dp">
        </item>

        <item>
            <shape android:shape="oval">
                <solid android:color="@color/colorAccent"/>
            </shape>
        </item>
    </layer-list>
</item>
</code>```

What did I do wrong?

Thanks in advance

答:
Must be because of the order, try it this way:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_pressed="true">
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="@color/colorAccent"/>
            </shape>
        </item>

        <item android:drawable="@drawable/ic_pause_black_24dp">
        </item>
    </layer-list>
</item>

<item android:state_pressed="false">
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="@color/colorAccent"/>
            </shape>
        </item>

        <item android:drawable="@drawable/ic_play_arrow_black_24dp">
        </item>
    </layer-list>
</item>
</code>```

Body:
I want to implement a toggle button that can pass from "start" to "pause" with the following design:

I put a ToggleButton, and I tried to use the following selector, but it does not work. In fact, only the circled background is displayed, but not the vector images (xml files) of the play and pause icons...

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_pressed="true">
    <layer-list>
        <item android:drawable="@drawable/ic_pause_black_24dp">
        </item>

        <item>
            <shape android:shape="oval">
                <solid android:color="@color/colorAccent"/>
            </shape>
        </item>
    </layer-list>
</item>

<item android:state_pressed="false">
    <layer-list>
        <item android:drawable="@drawable/ic_play_arrow_black_24dp">
        </item>

        <item>
            <shape android:shape="oval">
                <solid android:color="@color/colorAccent"/>
            </shape>
        </item>
    </layer-list>
</item>

What did I do wrong?

Thanks in advance

Body:
Must be because of the order, try it this way:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_pressed="true">
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="@color/colorAccent"/>
            </shape>
        </item>

        <item android:drawable="@drawable/ic_pause_black_24dp">
        </item>
    </layer-list>
</item>

<item android:state_pressed="false">
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="@color/colorAccent"/>
            </shape>
        </item>

        <item android:drawable="@drawable/ic_play_arrow_black_24dp">
        </item>
    </layer-list>
</item>


问:
jQuery::when I use fadeIn() my page moves its focus!
I have a simple HTML page, and some javascript using the basic $(#element).fadeOut method from jQuery on mouseover event. I also use the $(#element).hide() method.

But my page focus shifts up! Meaning: if I scroll down a bit, and mouseover the element (which toggles the script), script is executed well, but my scroller goes up immediately and I lose where I had scrolled to.

How can I fix this?

Here's my code:

```<code>function swapElements(unfadeElement, how, callbackExecute)
{
    if (unfadeElement==swapper.active)
    return;

    if (how!="slow" && how!="fast")
    return;

    var fadeElement=swapper.active;

    $("#" + fadeElement).hide();
    $("#" + unfadeElement).fadeIn(how,callbackExecute);
    swapper.active=unfadeElement;
}
</code>```

The fadeIn function:

```<code>function fadeInElement(element, how, callbackExecute)
{
    //pre: how is "slow" or "fast"
    if (how!="slow" && how!="fast")
    return;
    $("#"+element).fadeIn(how, callbackExecute);
}
</code>```

A sample script call:

```<code><a href="javascript: void(0)" onmouseover="fadeIn('carpets','slow',void(0))"> Carpets</a>
</code>```

EDIT: Added some of the HTML code

```<code>  <div id="menuDiv">
....................
                        <div id="menu1" class="menuDivLink">
                        <a href="javascript: void(0)" onmouseover="swapper.fadeIn('carpets','slow',void(0))"> Carpets</a>
                        </div>
                        <div id="menu2" class="menuDivLink">
                        <a href="javascript: void(0)" onmouseover="swapper.fadeIn('rugs','slow',void(0))">Rugs</a>
                        </div>
                        <div id="menu3" class="menuDivLink">
                        <a href="#" onmouseover="swapper.fadeIn('windows','slow',void(0))">Link1</a>
                        </div>
............
</div>
</code>```

Also, could some of my css cause this problem?
Thanks in advance

答:
Try using .animate() instead of fadeIn, something like

.animate({ opacity: 1 }, 300, callBackFunction);

Body:
I have a simple HTML page, and some javascript using the basic $(#element).fadeOut method from jQuery on mouseover event. I also use the $(#element).hide() method.

But my page focus shifts up! Meaning: if I scroll down a bit, and mouseover the element (which toggles the script), script is executed well, but my scroller goes up immediately and I lose where I had scrolled to.

How can I fix this?

Here's my code:

function swapElements(unfadeElement, how, callbackExecute)
{
    if (unfadeElement==swapper.active)
    return;

    if (how!="slow" && how!="fast")
    return;

    var fadeElement=swapper.active;

    $("#" + fadeElement).hide();
    $("#" + unfadeElement).fadeIn(how,callbackExecute);
    swapper.active=unfadeElement;
}

The fadeIn function:

function fadeInElement(element, how, callbackExecute)
{
    //pre: how is "slow" or "fast"
    if (how!="slow" && how!="fast")
    return;
    $("#"+element).fadeIn(how, callbackExecute);
}

A sample script call:

 Carpets

EDIT: Added some of the HTML code

....................

                         Carpets

                        Rugs

                        Link1

............

Also, could some of my css cause this problem?
Thanks in advance


问:
dll in c++, WINDOWS deployment / dependency's (mingw-w64 )
Background:
I'm programming a plugin (basically a dll) for an x64 application.
More specifically this x64 WIN application comes with a "plugin manager" (a dll) that loads and unloads 3rd party plugins (like mine).
My plugin is written in C++ and I decided to compile it with mingw-w64. As IDE I've choosen Code::Blocks.
I tried to avoid MS tools since later I need to deploy "the same" plugin on Linux and MAC (but that's another story lets focus on Windows for now).

Challenge:
There is one severe issue I can not resolve reliable with my knowledge/skill level, although I really worked hard in days of researches and tests: Dependency on WINDOWS dll's.
I must assure that this plugin runs on all WINDOWS versions from 7 to 10 (x64 only however).
The shipment of MS redistributables should be avoided since not practical in this case.
Apparently a static linking of the c-runtime library "MSVCRT.dll" seems to be neither allowed by copyright nor a reliable solution since there seam to be many different releases on the various WIN versions. Although Microsoft describes it as "known dll" I'm not sure which version is available where and which version is able to run on a certain Win version. And if a certain MSVCRT.dll runs, does it have enough "functionallity" for my plugin? (To high for me)

The question:
In your professional opinion what's is a reliable way to assure stability for my plugin on WINDOWS 7 to 10 (x64) in terms of Windows dll dependency's?
Are there other pitfalls I should worry about in the context of this dependency's on deployment.

Additional info:
Dependency walker_x64 (what a handy tool!) in this development stage of the plugin shows me dependency's on:

KERNEL32.DLL

MSVCRT.DLL (That's the guy I'm worried the most)

PM_64.DLL (That's the plugin manager of the x64 application)

On my computer (Windows 7 x64), MSVCRT.DLL shows version 7.0.7601.17744, OK, works. But if the customer has, say, a Windows 10 machine, freshly installed (not many MS redistributable versions available), will it work reliably?

I know that similar questions have been discussed before, especially on the c-runtime library "MSVCRT.dll". Many of them before WIN10 however.
The newlib idea (http://sourceware.org/newlib/) for example, 6years ago.
Mingw-w64 ships with archives called: libmsvcrt.a / libmsvcrtXXX.a. Is there a way with those?

I've read all I could find but I have to admit that now I have more doubts and questions than answers...
Your prefessional advice is appreciated. Thank you.

答: You may rely on presence and stability of at least the following dynamic libraries: kernel32.dll, msvcrt.dll, user32.dll, gdi32.dll. They are system libraries, present in C:\Windows\System32\ folder after the clean OS installation, and created by Microsoft as user API to interact with OS. MinGW library libmsvcrt.a (as well as non-static MS libraries) have no actual processing code but are just wrappers to call these DLLs from system folder.