text:
Q: Creating a slow reply from Dialogflow I want to create a Dialogflow webhook that responds to the user slowly, so it more feels like someone is on the other end and takes a few seconds to reply.
I'm using the built-in code editor, and can create an Intent handler (see code), but I just don't know how to get it to reply slower.
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  function welcome (agent) {
    agent.add(`I'm replying too quickly!`);
  }

  function fallback (agent) {
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  agent.handleRequest(intentMap);
});

A: Best way to handle this is to add delay in the UI code.
Keep the Dialogflow Intent as it is, and once the bot response is received on the frontend, show it with a delay.
Below is an example of how we are handling it at Kommunicate
Dialogflow response comes without any delay, then on Javascript code, we show a typing indicator animation, add some delay using Javascript before displaying it.

A: Needing to reply slower is rarely a desired thing, to be honest. But the easiest way to do so is to use setTimeout() and delay for a little bit. (Don't delay too long - more than 5 or 10 seconds and Dialogflow will timeout.)
The catch with using setTimeout(), however, is that the handler will need to return a Promise. So you'll need to wrap the call to setTimeout() and the agent.add() in a Promise handler. A function that does this might look something like:
function respondSlowly( agent, msg, ms ){
  return new Promise( resolve => {
    setTimeout( () => {
      agent.add( msg );
      resolve();
    }, ms );
  });
}

You would then call this from your handler, providing the agent, the message, and how many milliseconds to wait to reply:
function welcome( agent ){
  return respondSlowly( agent, `Hi there, slowly`, 2000 );  // Wait 2 seconds to reply
}


text:
Q: Entity Framework Core - Migration - No Parameterless Constructor Defined for this Object I am working with the latest .Net Core and EF Core in Visual Studio 2017.  I have created a model and it was working great.  I have since made some modifications and am getting the following error when I try to add a new migration:
Build succeeded.
  0 Warning(s)
  0 Error(s)

Time Elapsed 00:00:09.08
System.MissingMethodException: No parameterless constructor defined for this object.
  at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
  at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
  at System.Activator.CreateInstance(Type type, Boolean nonPublic)
  at System.Activator.CreateInstance(Type type)
  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_0.<FindContextTypes>b__3()
  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
  at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
  at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
  at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
No parameterless constructor defined for this object.

I have compared my code since the last check in and have commented out certain chunks of code to see if the error persists and whatever I comment out, it still fails with the same error.
Question: Is there a way to get more detailed information on exactly WHAT type does not have a parameterless constructor?  Or even run this from within VS and perhaps get a breakpoint?
Update: Based on some of the comments, here is some code.
For the DbContext override
public class AlmanacDb : IdentityDbContext<ApplicationUser, ApplicationRole, int> {

  private readonly ILogger logger;

  public AlmanacDb(DbContextOptions<AlmanacDb> options, ILoggerFactory loggerFactory) : base(options) {
    this.logger = loggerFactory.CreateLogger<AlmanacDb>();
  }

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
    optionsBuilder.UseSqlServer("Server=.\\SQLExpress;Database=Almanac;Trusted_Connection=True;MultipleActiveResultSets=True;");
  }

  ...
}

I do have a IDbContextFactory but it is not referenced anywhere and worked without a reference.  Not sure if this is a problem or not based on a link provided in the 2nd comment.  If memory serves, as long as the IDbContextFactory is within the solution, it should find it?
public class AlmanacDbFactory : IDbContextFactory<AlmanacDb> {

  private IConfigurationRoot configuration;
  private readonly ILoggerFactory loggerFactory;

  public AlmanacDbFactory(ILoggerFactory loggerFactory) {
    var builder = new ConfigurationBuilder()
     .SetBasePath(System.AppContext.BaseDirectory)
     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

    this.configuration = builder.Build();
    this.loggerFactory = loggerFactory;
  }

  public AlmanacDb Create(DbContextFactoryOptions options) {
    var optionsBuilder = new DbContextOptionsBuilder<AlmanacDb>();
    optionsBuilder.UseSqlServer(
      configuration.GetConnectionString("AlmanacSQL"), m => { m.EnableRetryOnFailure(); }
    );

    return new AlmanacDb(optionsBuilder.Options, loggerFactory);
  }
}

My Startup.cs class
public void ConfigureServices(IServiceCollection services) {
  try {
    services.AddDbContext<AlmanacDb>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("AlmanacSQL"))
    );
    services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

    services.AddIdentity<ApplicationUser, ApplicationRole>()
      .AddEntityFrameworkStores<AlmanacDb, int>()
      .AddDefaultTokenProviders();

    services.AddScoped<SignInManager<ApplicationUser>, AvantiaSignInManager<ApplicationUser>>();

    services.AddAuthorization(x => {
      x.AddPolicy("EmployeeOnly", p => p.RequireClaim("EmployeeNumber"));
    });

    services.AddMvc();
  } catch (Exception e) {
    Console.WriteLine(e.ToString());
    throw;
  }
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, AlmanacDb context) {
  ... // Nothing actually touches the AlmanacDb within this code so I left it out
}

Update 2: Solutiuon
Seeing that I am learning ASP.Net Core I am reading a ton of sites (including learn.microsoft.com) at one point I put in the IDbContextFactory code as you can see above.  I removed that from my code and the error went away and everything built and created the migration.
I am going to mark @alessalessio as the answer as I assume (have not tested it yet) that taking out the ILoggerFactory loggerFactory dependency within the AlmanacDbFactory constructor will do the trick as well.

A: If you have a separate project for context.
set a startup project with the target project
dotnet ef migrations add InitialCreate -s .\src\WebUI\  -p .\src\Infrastructure\ --verbose

A: Design-time tools attempt to automatically find how your application creates instances of your DbContext type. If EF cannot find a suitable way to initialize your DbContext, you may encounter this error.
Options:
1- Either create a parameterless constructor
  public AlmanacDb() { }
  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {
       optionsBuilder.UseSqlServer(_connString);
  }

  private readonly string _connString = "<your conn string>";

2-
public AlmanacDb Create()
{
     var optionsBuilder = new DbContextOptionsBuilder<AlmanacDb>();
     optionsBuilder.UseSqlServer(connectionString);

     return new AlmanacDb(optionsBuilder.Options);
}

https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

A: I had the same issue. My problem started when i changed my imeplementation of ApplicationUser to User with Guid Id.
public class User : IdentityUser<Guid>
First I started getting some crazy errors and after setting my DbContext to:
public class NgSchoolsContext : IdentityDbContext<User, IdentityRole<Guid>, Guid>
I started getting the "No parameterless constructor" error.
What finally fixed it was changing the Roles configuration in Startup:
services.AddIdentityCore<User>()
     .AddEntityFrameworkStores<NgSchoolsContext>()
     .AddRoles<IdentityRole<Guid>>()
     .AddDefaultTokenProviders();
Notice the IdentityRole part. You don't need to implement a thing, just put it like that. It should work out of the box.
HOWEVER!! Your migrations WILL fail and you'll have to rebuild your db from start. Entity can't handle the fact that all of his primary keys went from string(or whatever) to Guid and won't be able to update the database.
Well, that is at least easier to solve. Drop database, delete all migrations, Add-Migration (new initial) and Update-Database. This would be so easy if for normal error message.

A: I had the same error "No parameterless constructor defined for type ..." while trying to adda migration.
Turns out that when running ef migrations entity framework passes on arguments in the startup project Program.cs
The string[] args was removed for security reasons. Adding this resolved the issue.

A: Here's the error I was getting, sounds very similar to yours.
I had encountered this problem when trying to create a View (the one circled in red).  My issue was the Startup.cs file.   I had recently done a re-name from LeaveHistory... to LeaveRequest..., and when editing my Startup.cs file I made an incorrect change.

Line 39 should read:
services.AddScoped<ILeaveRequestRepository, LeaveRequestRepository>();  // no "I"

The error I was getting mentioned that the dbContext class didn't have a parameterless constructor - so it was totally deceptive, or at least not that helpful.
So to anyone else looking at this error, don't take it on it's face!  I am fairly deep into this project, and none of my other controllers have parameterless constructors, at least not written out.
Think about other clerical changes you've made - class name changes, things like that.   Check your Startup.cs file to make sure you've accounted for those changes correctly.  In my case I didn't, but the error message was not being helpful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: RealVNC - SSMS - Application Menu does not work When using RealVNC Viewer for remote connection I can't use SSMS' Menu. When clicking, for example, File, only thing it does is highlight if. But the drop-down menu doesn't work.
Tested with other solutions and it's clear this is VNC issue - RDP works as expected, same with TeamViewer. Same computers, same session on remote machine.
Anyone knows it's a bug, feature or some setting in VNC (Client or Server)?
Machine I'm connecting from is XPS8500 with windows 10 Pro, target is Windows 7 Pro on Optiplex 3040.
EDIT:
Versions:
Real VNC Server v 6.2.1 (r32538) x64.
Windows 7 Professional v6.1.7601 Service Pack 1 Build 7601
Microsoft SQL Server Management Studio (SSMS) 14.0.17224.0


text:
Q: SCSS How to create style on the fly I often use styles like next ones:
...
v-slot-padding-top4 {
    padding-top: 4px;
}

v-slot-padding-top16 {
    padding-top: 8px;
}
...

I can created many styles in cycle, but this way gives me many created styles that I'll never use.
Is there any way in scss to created styles on the fly? Or prepared something like function and call it from html attribute like class?

A: SCSS (Sass) is a preprocessor scripting language. It will be converted to CSS. You cannot dynamically create styles on the fly (runtime).
But you can use Sass features like @for. To create all your classes in range you need.
your.scss:
@for $i from 1 through 16 {
  .v-slot-padding-top#{$i} {
    padding-top: #{$i}px
  }
}

Result in CSS:
.v-slot-padding-top1 {
  padding-top: 1px;
}

.v-slot-padding-top2 {
  padding-top: 2px;
}

.v-slot-padding-top3 {
  padding-top: 3px;
}

.v-slot-padding-top4 {
  padding-top: 4px;
}

/* etc */


text:
Q: How to trigger Matlab with Jenkins I would like to create a Jenkins job which would trigger and open Matlab in my computer. As my machine runs Windows 10, I have to Execute a batch command at the Build section, and add a command which would trigger Matlab.
I am not exactly sure which is the command that I should put there. I know where Matlab is stored in my computer, but I am not sure how to use this. Any tips?

A: I would recommend you to read this blog, that explains how to setup a Jenkins continuous integration job for MatLab.
In the Execute a batch command, you should call something like this:
C:\Program Files\MATLAB\R2012a\bin\matlab.exe -nodisplay -r "disp('Hello World!');exit"


text:
Q: To get data from another activity The question I am asking might have already been asked but I have got stuck.
I want to pass data from EditText of one activity to ListView in another activity
how can I do that.
I have used intent putExtra and I am not able implement the get function
so can anyone tell me how to implement get function on ListView.
private static class ListViewAdapter extends BaseAdapter{

    private LayoutInflater Linflate;
    private Object convertView;

    public ListViewAdapter(Context context)
    {
        Linflate=LayoutInflater.from(context);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return ListViewContent.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View v, ViewGroup arg2) {
        final ListContent holder;

        if (v== null) {
            v = Linflate.inflate(R.layout.listviewinflator, null);

            holder = new ListContent();
            holder.text = (TextView) v.findViewById(R.id.TextView01);
           holder.text.setCompoundDrawables(v.getResources().getDrawable(R.drawable.ic_launcher), null, null, null);

            v.setTag(holder);

        } else {

            holder = (ListContent)v.getTag();
        }

        holder.text.setText(ListViewContent.get(position));

              return v;
    }

    static class ListContent {
        TextView text;

}

}
private static final ArrayList<String> ListViewContent = new ArrayList<String>();

}

on this i want to set get method.

A: Make a model class and serialize it.Pass object of that class
 putSerializable("object", object);

get object in second class -
Bundle bundel = getIntent().getExtras();
object = (myClass) bundel.get("object");


text:
Q: Why/how does the Longest Proper Prefix/Suffix algorithm work? The LPS (Longest Proper Prefix which is also a Suffix) algorithm goes as follows:
public static int[] constructLPSArray(String s) {
        int n = s.length();
        int[] arr = new int[n];
        int j = 0;
        for (int i = 1; i < n; ) {
            if (s.charAt(i) == s.charAt(j)) {
                arr[i] = j + 1;
                i++;
                j++;
            } else {
                if (j != 0) {
                    j = arr[j - 1];
                } else {
                    i++;
                }
            }
        }
        return arr;
    }

The if (s.charAt(i) == s.charAt(j)) part looks clear, but the else part is unclear.
Why do we do:
if (j != 0) {
  j = arr[j - 1];
} else {
  i++;
}

More specifically, why does j = arr[j - 1] work ? Or why do we even do it? How do we validate the correctness of this step?

A: Let's say we are parsing an array of characters with i and j positioned like this:
a b a b x x a b a b ...
      ^           ^
      j           i

with arr holding:
0 0 1 2 0 0 1 2 3 4

i. e., the length of the longest prefix/suffix of each substring of s of that length until i. You can probably guess how that was generated from the rest of the algorithm. Now, if the next character after i does not match the next character after j,
a b a b x x a b a b a ...
        ^           ^
        j           i

we don't have to retry the matching, because we know the longest prefix/suffix of our previous prefix/suffix! Looking up arr[j - 1] yields 2 – so we essentially cached the information that the parts highlighted here
A B a b x x a b A B a ...
=== ^           === ^
    j               i

are identical, and don't need to be compared again!

A:   *Here's one more solution*
  int length=str.length();
  int mid=length/2;
  if(length<2){
       System.out.println("-1");
  }
  for(int i=mid;i>=0;i--){
      String prefix=str.substring(0,i);
      String suffix=str.substring(length-i,length);
      if(suffix.equals("") || prefix.equals("")){
            System.out.println("-1");
      }
      if(suffix.equals(prefix)){
          System.out.println(suffix.length());
          break;
      }

  }


text:
Q: Explicit examples of warped products Gromov converge to a cone It's well known that a sequence of two dimensional Riemannian manifolds with uniform sectional curvature lower bound can Gromov-Hausdorff converge to a cone.
Let $y=|x|$, by rotating around the y-axis, we get a cone $X$. Now I want to construct functions $y=f_i(x)$ such that their rotations around the y-axis (denoted by $M_i$) are smooth Riemannian manifolds and Gromov-Hausdorff converge to the cone $X$. I also want to compute the Gaussian curvature of $M_i$.
I considered $f_i(x)=|x|^{a_i}$ such that $a_i>1$ decrease to 1, but $f_i''(0)=\infty$, so it's not smooth enough, and the curvature at $x=0$ can't be defined.
I also considered mollification of $|x|$ by convolution of $\eta(x)=c\exp(\frac{1}{|x|^2-1})$, but we can't write down the explicit form of the integration.
Can any one give good approximations such that $f_i(x)$ can explicit be written down?
Thanks to Thomas Richard's answer, below we compute the Gaussian curvatures. Let $y=\sqrt{t^2+a^2}$, then the length of the curve
$$
l(t)=\int_0^t \sqrt{1+[y'(t)]^2}=\int_0^t (2t^2+a^2)^{\frac12}(t^2+a^2)^{-\frac12}dt
$$
The metric can be written as $dl^2+t^2 d\theta^2$, by the curvature formula of the warped products, and note that $t''(l)=-\frac{l''(t)}{(l'(t))^3}$, the Gaussian curvature
$$
K=-\frac{t''(l)}{t}=\frac{l''(t)}{(l'(t))^3 t}=\frac{2a^2}{(2t^2+a^2)^2}.
$$
At $t=0$, $K=\frac{2}{a^2}\to \infty$ as $a\to 0$.

A: What about $f(x)=\sqrt{x^2+\varepsilon_i^2}$ with $\varepsilon_i$ going to zero ?
If you want to vary the angle of the limit cone, consider $f(x)=C\sqrt{x^2+\varepsilon_i^2}$.


text:
Q: spark taking a long time for reading a compressed json on HDFS I have 2 compressed jsons files (bz2) on HDFS. I have to load them in Spark. For this, first I have started pyspark (shell) and then perform following queries for this:
>> df = spark.read.load("hdfs://master:9000/data/db1/file_part*.bz2", format="json", sep=",", inferSchema="true")
    [Stage 0:>                              (8 + 4) / 503]

As it can be seen that it is loading data. Why this is happening. According to my knowledge, spark does not perform anything before action (as it is lazy), then there are 503 stages in this case. I have to create a data frame and then convert into a tempView. After this using SQL, perform some operation of SQL. In my case, almost all setting is default.
Remaining sections of data processing are as follows:
df.createOrReplaceTempView("view1")
sqlContext.sql("select count(distinct(id)) from view1").show()

A: The Optimizer with DFs and such differs to that of RDD processing. It can and does sometimes launch Stages ahead of an Action now where DFs are concerned. Zipped files, inferring schema and pivots, for example.

In this case there is a case of wanting to infer schema. That is a
slow process.

*

*You can supply the schema which will then save time.

*Or use a sampling percentage when inferring is specified; then this will be faster but you run the risk of not getting the overall correct schema.


text:
Q: Android Maven build gives trouble processing "javax/xml/namespace/QName.class": Following error is showing in Maven console everytime I do Project -> Clean. Only the jar file is built in the target folder, apk file is not getting built.
Can anyone please help me to solve this issue?
Regards,
Sam.
My development environment is;

*

*Eclipse Helios

*Android SDK API level 8

*Eclipse ADT 10.0.1

*Maven Integration for Android Development Tools 0.2.5

4/30/11 9:54:07 PM IST: [INFO] skip non existing resourceDirectory D:\my\workspace\android\android-test-app\src\test\resources
4/30/11 9:54:07 PM IST: [INFO] Not compiling test sources
4/30/11 9:54:07 PM IST: [INFO] Tests are skipped.
4/30/11 9:54:07 PM IST: [INFO] D:\my\android-sdk-my\android-sdk-windows/platform-tools/dx.bat [--dex, --output=D:\my\workspace\android\android-test-app\target\classes.dex, D:\my\workspace\android\android-test-app\target\android-classes]
4/30/11 9:54:17 PM IST: [INFO]
4/30/11 9:54:17 PM IST: [INFO] trouble processing "javax/xml/namespace/QName.class":
4/30/11 9:54:17 PM IST: [INFO]
4/30/11 9:54:17 PM IST: [INFO] Ill-advised or mistaken usage of a core class (java.* or javax.*)
4/30/11 9:54:17 PM IST: [INFO] when not building a core library.
4/30/11 9:54:17 PM IST: [INFO]
4/30/11 9:54:17 PM IST: [INFO] This is often due to inadvertently including a core library file
4/30/11 9:54:17 PM IST: [INFO] in your application's project, when using an IDE (such as
4/30/11 9:54:17 PM IST: [INFO] Eclipse). If you are sure you're not intentionally defining a
4/30/11 9:54:17 PM IST: [INFO] core class, then this is the most likely explanation of what's
4/30/11 9:54:17 PM IST: [INFO] going on.
4/30/11 9:54:17 PM IST: [INFO]
4/30/11 9:54:17 PM IST: [INFO] However, you might actually be trying to define a class in a core
4/30/11 9:54:17 PM IST: [INFO] namespace, the source of which you may have taken, for example,
4/30/11 9:54:17 PM IST: [INFO] from a non-Android virtual machine project. This will most
4/30/11 9:54:17 PM IST: [INFO] assuredly not work. At a minimum, it jeopardizes the
4/30/11 9:54:17 PM IST: [INFO] compatibility of your app with future versions of the platform.
4/30/11 9:54:17 PM IST: [INFO] It is also often of questionable legality.
4/30/11 9:54:17 PM IST: [INFO]
4/30/11 9:54:17 PM IST: [INFO] If you really intend to build a core library -- which is only
4/30/11 9:54:17 PM IST: [INFO] appropriate as part of creating a full virtual machine
4/30/11 9:54:17 PM IST: [INFO] distribution, as opposed to compiling an application -- then use
4/30/11 9:54:17 PM IST: [INFO] the "--core-library" option to suppress this error message.
4/30/11 9:54:17 PM IST: [INFO]
4/30/11 9:54:17 PM IST: [INFO] If you go ahead and use "--core-library" but are in fact
4/30/11 9:54:17 PM IST: [INFO] building an application, then be forewarned that your application
4/30/11 9:54:17 PM IST: [INFO] will still fail to build or run, at some point. Please be
4/30/11 9:54:17 PM IST: [INFO] prepared for angry customers who find, for example, that your
4/30/11 9:54:17 PM IST: [INFO] application ceases to function once they upgrade their operating
4/30/11 9:54:17 PM IST: [INFO] system. You will be to blame for this problem.
4/30/11 9:54:17 PM IST: [INFO]
4/30/11 9:54:17 PM IST: [INFO] If you are legitimately using some code that happens to be in a
4/30/11 9:54:17 PM IST: [INFO] core package, then the easiest safe alternative you have is to
4/30/11 9:54:17 PM IST: [INFO] repackage that code. That is, move the classes in question into
4/30/11 9:54:17 PM IST: [INFO] your own package namespace. This means that they will never be in
4/30/11 9:54:17 PM IST: [INFO] conflict with core system classes. JarJar is a tool that may help
4/30/11 9:54:17 PM IST: [INFO] you in this endeavor. If you find that you cannot do this, then
4/30/11 9:54:17 PM IST: [INFO] that is an indication that the path you are on will ultimately
4/30/11 9:54:17 PM IST: [INFO] lead to pain, suffering, grief, and lamentation.
4/30/11 9:54:17 PM IST: [INFO]
4/30/11 9:54:17 PM IST: [INFO] 1 error; aborting

A: If your are using android maven integration, you should add the "provided" scope in your android sdk dependency.
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>

A: You can exclude implicit dependencies using the exclude-tag. QName seems to be in e.g. the xpp3 package. I solved this problem by adding the following exclusions to my pom (that already contained the dependency to google-api-client-googleapis):
<dependency>
  <groupId>com.google.api.client</groupId>
  <artifactId>google-api-client-googleapis</artifactId>
  <version>1.4.1-beta</version>
  <exclusions>
    <exclusion>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </exclusion>
    <exclusion>
      <groupId>xpp3</groupId>
      <artifactId>xpp3</artifactId>
    </exclusion>
</exclusions>
</dependency>

If you need to find where the conflicting class files come from, run for example:
for x in `find ~/.m2/repository/ -name \*.jar`; do jar tf $x|grep QName.class && echo "Found in: $x"; done`


text:
Q: Let $Z\in \mathcal{N}(0,I)$ and $A=\{(x_1,x_2,x_3): x_1\le x_2 \le x_3 \}$. Show $P(Z+\mu \in A) \le P(Z \in A)$ is $\mu \notin A$. Suppose that $A=\{(x_1,x_2,x_3):  x_1\le x_2 \le x_3 \}$.  Let $Z \in \mathbb{R}^3$ be a standard normal random vector.
I am trying to see if the following inequality is true
\begin{align}
P(Z+\mu \in A) \le  P(Z \in A)
\end{align}
for all $\mu \notin A$.
My intuition: I am thinking of $Z$ as a ball centered at zero and $A$ as a cone starting at zero.  If we move a center of the ball farther from the cone, then the intersection (probability) should go down.

A: The inequality is false. Consider $\mu = (0, -\epsilon, C)$ for some really small $\epsilon > 0$, and some really large $C$, which is not in $A$ for any $\epsilon, C$. Now, the probability of $Z + \mu$ being in $A$ will tend to 1/2 as $C$ grows to infinity and $\epsilon$ goes to 0. Probability $Z$ is in $A$ is exactly 1/6 though.


text:
Q: Create Rush Hour function from numeric hours I'm currently working on a problem where I have a column called hr (hours) which is numeric and lists hours from 0:23. What I would like to do is create another characterized column that gives "Yes" if hours are between 16 and 18 (rush hour) and "No" for all other times. I then want to tally up how many registered bike users (registered) there are during these times. I have tried the following code below however it does not give the desired output. I have also attached an image of my full dataframe. Any help would be appreciated and apologies if question is worded poorly as I am new to R and the StackOverflow community
bike_df %>%
 filter(hr > 15 | hr < 19) %>%
  tally(bike_df$registered)

A: A couple of options depending on whether you want the output summarised or not:
(%>% may be used instead of |>.)
library(tidyverse)

bike_df <- tribble(
  ~hr, ~registered,
  15, 100,
  15, 101,
  16, 200,
  16, 201,
  18, 300,
  18, 301,
  20, 400,
)

# Summarised
bike_df |>
  mutate(rush_hour = if_else(between(hr, 16, 18), "Yes", "No")) |>
  group_by(rush_hour) |>
  summarise(registered = sum(registered))
#> # A tibble: 2 × 2
#>   rush_hour registered
#>   <chr>          <dbl>
#> 1 No               601
#> 2 Yes             1002

# Unsummarised
bike_df |>
  mutate(rush_hour = if_else(between(hr, 16, 18), "Yes", "No")) |>
  add_count(rush_hour, wt = registered, name = "rush_reg")
#> # A tibble: 7 × 4
#>      hr registered rush_hour rush_reg
#>   <dbl>      <dbl> <chr>        <dbl>
#> 1    15        100 No             601
#> 2    15        101 No             601
#> 3    16        200 Yes           1002
#> 4    16        201 Yes           1002
#> 5    18        300 Yes           1002
#> 6    18        301 Yes           1002
#> 7    20        400 No             601

Created on 2022-08-22 with reprex v2.0.2


text:
Q: hide and show the div depending on the button using jquery i need to hide and shoe the div depending on the button using html and jquert
is the button name=show status i click the button change to the name=hide  and display the div, the same function in reverse also

A: You could do something like this (Note the custom display attribute):

$("#btn").click(function() {
   var item = $("input[name=yourInput]");

   if (item.attr("display")) {
      item.show();
      item.attr("display", false);
   } else {
        item.hide();
        item.attr("display", true);
    }
});

<input name="yourInput" display="true" />

http://jsfiddle.net/Jrz5Y/1/

A: You can create a boolean variable set to a default value, and change it to it's inverse value whenever you click on the button.
depending on the state of the boolean you can execute the correct path in your method

A: you can use this
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">

    function ShowHide()
    {
            if ($("#divdata").css('display') == 'none'){
            $("#divdata").show();
            $("#btnClick").val("Hide");
        }
        else{
            $("#divdata").hide();
            $("#btnClick").val("Show Status");
        }
}

</script>

your div will be like this.
<div id="divdata" style="display:none">
I have to show and hide this div.
</div>

Button will be like this.
<input id="btnClick" type="button" value="Show Status"   onclick="ShowHide()" />

I hope It will work.


text:
Q: TypeScript error in angular: A function whose declared type is neither 'void' nor 'any' must return a value I'm trying to highlight dates on a calendar. I'm using angular-material-datepicker with dateClass.
The logic is fine but I can't figure out why I'm getting the below error. Can anyone please tell me why I'm getting the below error?
A function whose declared type is neither 'void' nor 'any' must return a value.

HTML:
<mat-calendar *ngIf="loadCalendar" [dateClass]="dateClass()" [selected]="selectedDate" (selectedChange)="onSelect($event)"></mat-calendar>

Ts:
import { DatePipe } from "@angular/common";
import { Component, OnInit } from "@angular/core";
import { MatCalendarCellCssClasses } from "@angular/material";
import { DataService } from "../app/services/data.service";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
  providers: [DatePipe],
})
export class AppComponent implements OnInit {
  cardData;
  dates: string[] = [];
  loadCalendar: boolean = false;
  constructor(private data: DataService, public datepipe: DatePipe) {}
  ngOnInit() {
    this.data.getData().subscribe((data) => {
      this.cardData = data;
      this.cardData.forEach((element) => {
        //  console.log(this.datepipe.transform(element.start, 'yyyy/MM/dd'));
        this.dates.push(element.start);
        this.loadCalendar = true;
      });
    });
  }

  dateClass() { //Error is caused by this function
      return (date: Date): MatCalendarCellCssClasses => {

        this.dates.forEach((sD)=>{

          let startDate = this.datepipe.transform(sD, "yyyy/MM/dd");
          let calendarDate = this.datepipe.transform( date.getDate(),"yyyy/MM/dd");

          if (calendarDate === startDate) {
            return "special-date";
          } else {
            return "";
          }
        })

      };
  }
}

A:  return (date: Date): MatCalendarCellCssClasses => {  <-- !!!You say it returns a MatCalendarCellCssClasses

        this.dates.forEach((sD)=>{

          let startDate = this.datepipe.transform(sD, "yyyy/MM/dd");
          let calendarDate = this.datepipe.transform( date.getDate(),"yyyy/MM/dd");

          if (calendarDate === startDate) {
            return "special-date";
          } else {
            return""
          }

        })
       return "" <--- you must also return something here incase forEach does not loop
}

Edit: Updated answer as question was updated


text:
Q: Mobile website and desktop website : do I have to duplicate my code? I have a website built with Symfony2 and I would like to create a mobile version of it using jQuery mobile (I'm currently using Twitter bootstrap for the desktop version).
I'm really confused about the solution I have to choose :

*

*create a subdomain, for example : http://mobile.mywebsite.com and create another Symfony project which would be very similar but with just other html.twig files (to integrate jQuery mobile), but that means that I would duplicate a big part of my code ?

*media queries inside my symfony project in html files to use jquery mobile elements according to screen size. Thus, I would have only one project to maintain.
Any advice would be great ! Thanks !

A: Best practice is to create one page with a responsive design (media queries are part of that) that can adapt to any screen size.
You definitely should not be making a second Symfony project. You are essentially trying to make 2 different layouts for your site, so they should only affect your view. If you don't want to use a responsive design, you can create twig templates for your mobile pages and load those from the same controllers you use for the desktop site.

A: You can do routing based on the domain name:
http://symfony.com/doc/master/components/routing/hostname_pattern.html
With this you can have different controllers for the mobile site but still re-use your model and (at least some of) your view. You could even re-use some of the controllers by setting a parameter (based on the host) in the routing and then using that in the controllers:
# routing.yml

mobile_homepage:
    path:     /
    host:     m.{domain}
    defaults: { _controller: AcmeDemoBundle:Main:homepage, mobileVersion: true }
    requirements:
        domain: %domain%

homepage:
    path:  /
    defaults: { _controller: AcmeDemoBundle:Main:homepage }

Then in your controller:
// Acme/DemoBundle/Controller/MainController.php

public function homepageAction($mobileVersion = false) {
  ...
  if ($mobileVersion) {
    // do some mobile things, perhaps return a specific template
  } else {
    // do some non-mobile things, perhaps return a specific template
  }
  ...
}

A: I know it's a bit late but it still may be usefull for others.
I had the same question this morning and Google gave me MobileDetectBundle https://github.com/suncat2000/MobileDetectBundle/ which seems to solve that kind of problem. Not tryed yet but I will for sure !


text:
Q: Appeal of OS X for *nix developers? This question is for experienced Unix/Linux developers.
If you have found that you like Mac OS X better than *nix as a development platform, why is that?
I know that hardware configuration is more convenient and graphics are generally more polished, but I'm not referring to those things. I'm asking specifically about functionality related to software development.
Also, do the benefits still apply if you are mainly targeting Windows or Unix/Linux?

A: For most purposes, OS X is Unix. Aside from Xcode (which I personally don't care for), there isn't really anything there to make it better or worse than any other Unix-like system for development.
Most of the typical tools, libraries, languages, and interfaces are there, you'll even be using GCC for C/C++ work. As long as you're not developing against Apple/OS X-specific interfaces like Cocoa, you are developing on Unix.
I use OS X because it just works, thus not interfering with my development, not because it has magical fairy dust that makes it better than any other Unix for development.

A: I love Apple as a dev platform because I get all the power of the *nix commandline as well as Apple's developers tools (XCode).
The additional software/hardware polish, and quality of third party software make it all that much more enjoyable.

A: Mac OS X is not better than a Unix environment, it is a Unix environment: http://www.opengroup.org/openbrand/certificates/1190p.pdf
I'd go as far as saying it's probably the most used Unix, considering it's also in all iPod Touch and iPhones.
(As far as I'm aware, Linux isn't a certified Unix, but I may be wrong, perhaps a distribution/vendor went through that process.)
Sometimes, for professional reasons, you just have to have tools that are compatible with what your boss or customers use. This often includes proprietary tools like MS Office, whether you want it or not (OpenOffice can't always deal perfectly with Word documents). OSX provides this intermediate ground, where the developers can also be users or closer to their user base.


text:
Q: How to translate JavaScript ('object') into Python? I am working on converting some JavaScript code into Python.
There is an if condition in the JavaScript that looks something like:
if (typeof f === 'object') and then a series of actions are taken if this condition evaluates to true.
In this case f would be something like:
f = { 'fields': ["user_id", "date_started", "date_ended"] }
In this case f is a dict, but it might not always be the case.
I know that in JavaScript nearly everything is considered an object.
What would be the equivalent constraint to object in Python?

A: In JavaScript typeof f == 'object' is true when all of the following is not true:

*

*f is undefined: there is no equivalent in Python

*f is a number, bigint or boolean: in Python this is an instance of float or int. As bool is a subclass of int, it is included.

*f is a string: in Python this is an instance of str

*f is a symbol: there is no equivalent in Python

*f is a function: in Python you can use callable to detect this

Caveat: typeof null == 'object' is true, so in Python None should pass the equivalent test.
So this brings us to the following test in Python:
if not (callable(f) or isinstance(f, (int, float, str))):
    # it is an "object"

A: you can use type method for getting type of variables in python:
if (type(f) is dict)

Actually, js objects in python are dictionaries! you can see more details from this link.


text:
Q: Benefits of an async ServiceBusTrigger I'm working on microservices (using Azure Function Apps) that contain ServiceBusTrigger-based Azure Functions that trigger when a message is inserted into a Service Bus Queue.
I'm trying to determine the best way of binding output values to multiple targets (e.g. CosmosDB and IoT Hub). Whether or not the method is marked as async will determine how I should approach this problem.
As far as I am aware, the way that you would typically handle output binding with an async function is by using the [return: ...] annotation; however, in my use case, I need to return two different values to two separate targets (e.g. CosmosDb and IoT Hub). I don't think that this is something that I can achieve with return value binding or output variable binding, since you can't have an out param with an async method and you can define multiple return values with the [return: ...] approach.
It would seem that my only option (if I went the async route) would be to manually invoke SDK methods in the Azure Function to call the services independent of any output values. I'm trying to avoid doing that, seeing as output binding is the preferred approach.
An observation that I have made when creating a brand new ServiceBusTrigger-based Azure Function is that the generated method signature is not marked as async by default.
This is different than an HttpTrigger, which is marked as async out-of-box.
Can someone help me understand the reasoning for this? What are the scaling implications associated with one vs. the other?
I understand in a traditional sense why you typically mark an HttpTrigger as async; however, I don't understand the reasoning as to why the ServiceBusTrigger is not async
I need to understand this bit before I can move on with solidifying my approach to outputs.

A: I don't think templates with/without async functions have any reasoning to them as such. And depending on your code, your function may be more efficient.
Read this thread for more details on async/await in functions.
As for your main question, you just have to bind to different objects for the CosmosDB and IoT Hub output bindings.

*

*For CosmosDB, you will have to bind to IAsyncCollector instead as shown in the docs

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace CosmosDBSamplesV2
{
    public static class WriteDocsIAsyncCollector
    {
        [FunctionName("WriteDocsIAsyncCollector")]
        public static async Task Run(
            [QueueTrigger("todoqueueforwritemulti")] ToDoItem[] toDoItemsIn,
            [CosmosDB(
                databaseName: "ToDoItems",
                collectionName: "Items",
                ConnectionStringSetting = "CosmosDBConnection")]
                IAsyncCollector<ToDoItem> toDoItemsOut,
            ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed {toDoItemsIn?.Length} items");

            foreach (ToDoItem toDoItem in toDoItemsIn)
            {
                log.LogInformation($"Description={toDoItem.Description}");
                await toDoItemsOut.AddAsync(toDoItem);
            }
        }
    }
}

*

*For Event Hub, you will have to bind to IAsyncCollector instead as shown in the docs

[FunctionName("EH2EH")]
public static async Task Run(
    [EventHubTrigger("source", Connection = "EventHubConnectionAppSetting")] EventData[] events,
    [EventHub("dest", Connection = "EventHubConnectionAppSetting")]IAsyncCollector<string> outputEvents,
    ILogger log)
{
    foreach (EventData eventData in events)
    {
        // do some processing:
        var myProcessedEvent = DoSomething(eventData);

        // then send the message
        await outputEvents.AddAsync(JsonConvert.SerializeObject(myProcessedEvent));
    }
}


text:
Q: django can't serialize non-model on post New to django and trying to send an list of id's to the server to update some information.  I do not want them to be a model class, theres no need for it.  What I am trying to do is put them into a serializer to make sure they are "clean".  Here is my code:
View Class:
class Update_Cards(APIView):
    # This seems necessary or it will throw an error
    queryset = Card.objects.all()
    def post(self, request, board_id, format=None):
        print request.DATA
        serializer = CardMoveSerializer(data=request.DATA, many=True)
        #this throws an error
        print serializer.data

        return Response(serializer.data)

Serializer:
class CardMoveSerializer(serializers.Serializer):
    card_id = serializers.IntegerField()
    lane_id = serializers.IntegerField()

Error I get:
[{u'lane_id': 21, u'card_id': 3}] #this is to show the data is coming across the wire
Internal Server Error: /api/board/2/updateCards
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 77, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 327, in dispatch
    response = self.handle_exception(exc)
  File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 324, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/crob/Documents/workspace/tlckanban/python/rest/views.py", line 37, in post
    print card_moves.data
  File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 499, in data
    self._data = [self.to_native(item) for item in obj]
TypeError: 'NoneType' object is not iterable

What I have done is implemented this with a simplejson parser for now, but I feel like its not the best way to do it:
def update_cards(request, board_id):
    json_data = simplejson.loads(request.body)

    for moveIndex in range(0, len(json_data)):
        #do some work

    return JSONResponse(json_data, status=status.HTTP_200_OK)

Thanks for the help in advance!

A: You need to be accessing 'serializer.is_valid()' before accessing the data. Looks like there's a missing bit of API there - serializer.data should probably raise an expection if its accessed before validation.

A: Seems you are not using Django's serializers but anyway serialization is not made for validation. Use forms to validate your data then use json as you do to serialize it. Django's serializers are for querysets and models only.


text:
Q: Get table to fill remaining width I'm having a bit of trouble getting my table to fill the remaining space within a floated element. This is what I'm trying to achieve:

And this is what I have so far:
HTML:

                1
                2

CSS:
.parent {
    height: auto;
    overflow: hidden;
}
.left {
    width: 125px;
    background: blue;
    float: left;
    height: 100px;
}
.right {
    background: red;
    height: 100px;
}
table {
    background: green;
    /*width: 100%;*/
}

I tried width: 100% but that doesn't take into account the left-floated element and the table gets hidden outside the container. I also tried display: block but that causes the  to no longer function as they would if they were inside a table.
jsFiddle

A: As you are floating your .left div with the fixed width you can use a combination of the overflow:auto and width:auto (default value) to expand your .right div. Also uncomment width:100% to make table take the full width of the .right div:
.right {
  overflow:auto;
}

table {
  width: 100%;
}

Example


text:
Q: Visual C++ Statement + Vars How Can I bind for example int value to the statement below?
System::String^ Content = "just example";
int iAValue = 5;

lblOutput_{iValue}->Text = Content;

A: You don't; you use an array or collection of some sort.  This sort of thing is often attempted by beginners.  It is not possible, nor is it a good idea to tie your program logic to the names of your variables.
auto labels = gcnew List<Label>();
labels->Add(lblOutput1);
labels->Add(lblOutput2);
labels->Add(lblOutput3);
labels->Add(lblOutput4);
labels->Add(lblOutput5);
// ...
String^ Content = "just example";
int iAValue = 4;
labels[iAValue].Text = Content;

And then later you can iterate over all of them easily:
for(int i = 0; i < labels->Count; ++i) {
    // i is the label "number"
    // labels[i] is the label
}


text:
Q: Slow working on join query same table when large of dataset ( want to faster then )? This query is maintain below table
SELECT A.XXX as XXX,B.total_result as total_cost
FROM TABLE  as A
LEFT JOIN
(
    SELECT XXX,sum(`click`)*price as total_result
    FROM TABLE
    WHERE main_id = '1'  AND (DATE(`click_time`) BETWEEN '2017-11-01' AND '2017-11-30' OR `click_time` IS NULL)
    GROUP BY XXX,price
) B ON B.`XXX` = A.`XXX`
where B.click IS NOT NULL
GROUP BY A.XXX
LIMIT 0,20

Table
    k_id    main_id     XXX      click  price   click_time
        1     1         aaa         1   0.25    2017-11-05
        2     1         bbb         1   0.36    2017-11-05
        3     1         bbb         1   0.45    2017-11-05
        4     1         aaa         1   0.36    2017-11-05
        5     1         ccc         1   0.98    2017-11-05
        6     1         bbb         1   0.55    2017-11-05
        7     1         aaa         1   0.25    2017-11-05
        8     1         ccc         1   0.98    2017-11-05
        9     1         aaa         1   0.25    2017-11-05
        10    1         bbb         1   0.45    2017-11-05

I want to this query modify working this table of large dataset

A: There are few things you can do to optimize this query.
On the query side:
Avoid ordering if possible - I can see you have a GROUP BY clause in the subquery, but no ORDER BY clause. If you do not really care about the order of the results in the subquery, add the following order clause to the end of the subquery, which will tell MySQL not to use the default order and improve performance.
ORDER BY NULL

====
Avoid calling functions on potentially indexed columns - as it won't allow MySQL to use the index on that column. The following condition:
DATE(`click_time`) BETWEEN '2017-11-01' AND '2017-11-30'

Can be modified to this one, to avoid using the DATE function on the indexed column and instead only use functions on constant values:
click_time >= DATE('2017-11-01') AND click_time < (DATE('2017-11-30') + INTERVAL 1 DAY)

====
Do not use OFFSET values in your query - Instead of LIMIT X,Y, you can use the alternative approach for faster pagination with offset in MySQL.
===
Use numeric values whenever appropriate - When comparing a numeric column to a string, you're forcing MySQL to cast the column's value for each row from a number to a string and only then perform the comparison. Therefore, in the condition main_id = '1', if main_id is a numeric column, the condition should be:
main_id = 1

Instead of:
main_id = '1'

===
Also, if you can provide the schema structure, it will be possible to recommend the appropriate indexes for this situation.
By the way, I got the recommendations from this online MySQL query optimizer, so feel free to just enter your query and schema there to get indexing recommendations as well (you didn't provide the schema structure, otherwise I would have provided the indexing recommendations as well).


text:
Q: How to adjust the font size of stargazer tables in rmarkdown? If I am not mistaken, the font size argument in stargazer is ignored in rmarkdown documents:
Does somebody know how to fix this?
See also here
How to resize tables generated by Stargazer in R Markdown?
---
title: "Untitled"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library("stargazer")
m <- lm(speed~dist, cars)
```

```{r, results='asis'}
stargazer(m, type = "html", font.size="tiny", single.row = T)
stargazer(m, type = "html", font.size="Huge", single.row = T)
```

```{r, results='asis'}
print(stargazer(m, type = "html", single.row = T), scalebox='0.7')
```

A: Just add this to the end of your YAML, adjusting the font size as you wish:
---
title: "Untitled"
output: html_document
---

And the larger font will render:

A: I think that the font.size argument in stargazer is only used when rendered in Latex.
Instead when rendering to HTML you have to add a style element to the appropriate tag, in this case td for the table cell, th for the table header, or table for the entire table.
After the YAML header add the following css:

Or, if you want e.g. large table headers:

A: Since the output is html it is necessary to have some knowledge about handling tables in html you can see here, so place the code  at the top of the table.

---
title: "Untitled"
output: html_document
---

```{r cars, include=F}
library(stargazer)
stargazer(cars, type = "html", out="test.html", out.header=TRUE)
```

Statistic	N	Mean	St. Dev.	Min	Pctl(25)	Pctl(75)	Max

speed	50	15.400	5.288	4	12	19	25

dist	50	42.980	25.769	2	26	56	120


text:
Q: The type or namespace name 'DirectX' does not exist in the namespace 'Microsoft' Windows 8.1 I'm trying to draw some boxes in 2D in C#, but when I try the following:
using Microsoft.DirectX;
using D3D = Microsoft.DirectX.Direct3D;

I get the error:

The type or namespace name 'DirectX' does not exist in the namespace 'Microsoft'

Apparently I need the DirectX SDK but I'm on Windows 8.1 and the downloads are for Windows XP.

A: Starting with Windows 8, the DirectX SDK is included as part of the Windows SDK.
Therefor you will need to download the Windows SDK as described in the following MSDN article:
http://msdn.microsoft.com/en-us/library/windows/desktop/ee663275%28v=vs.85%29.aspx
You can find the download link here:
http://msdn.microsoft.com/en-us/windows/desktop/aa904949

A: Managed DirectX 1.1 is deprecated. It has a number of limitations:

*

*No support for .NET 4.x or later (it was written for .NET 1.1 and basically  works with .NET 2.0 and 3.x) which means it doesn't work with VS 2010 or later.

*No support 64-bit (x64) apps

*No support for Direct3D 10.x or 11.x (it was last updated in April 2006)

*No support for Windows Store apps, Windows phone apps, or Xbox One

*It depends on the legacy D3DX9 library

*The assemblies can only be deployed via the legacy DirectSetup and that requires the .NET 3.x runtime is enabled (which is off by default on Windows 8.x). See DXSETUP Update
If you want a more modern drop-in replacement for the legacy MDX assemblies, see SlimDX. SharpDX is another option and works for Windows Store apps / Windows phone apps.
See DirectX and .NET
Note that you can use the legacy DirectX SDK with the current Windows 8.x SDKs that come with VS 2012 or VS 2013 for C++, but this requires some editing of C++ paths. See MSDN


text:
Q: Android View is still getting OnClick() even by set its visibility to GONE I know there are few questions regard this issue but all of them are using animation. I have no animation at all in my activity. I have a TextView that by default is visible and is set to Gone based on a Feature-Flag that I get in my Splash screen.
This is my xml file:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/profile_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/profile_bg"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:paddingTop="?android:actionBarSize">

    <TextView
            android:id="@+id/payments_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="6dp"
            android:background="@drawable/profile_payment_bg"
            android:clickable="true"
            android:drawableLeft="@drawable/ic_profile_payment"
            android:drawablePadding="8dp"
            android:gravity="center_vertical"
            android:onClick="onClick"
            android:padding="8dp"
            android:text="Payment"
            android:textAppearance="?android:textAppearanceMedium"
            android:textColor="@android:color/white" />

...

    </LinearLayout>

</FrameLayout>

Although I'm setting Clickable and OnClickListener functionality to false and null respectively, OnClick() functionality is called even when my Payment button is not visible :(
@Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_profile);

        this.mPayments = (TextView) findViewById(R.id.payments_btn);

        // Check if payment functionality available for the Passenger
        final PassengerFeatureResponse cachedFeature = FeatureResponse.fromJsonString(PreferenceUtils.getFeatureResponse(this));
        if (cachedFeature == null || !cachedFeature.isMade())
        {
            this.mPayments.setVisibility(View.GONE);
            this.mPayments.setClickable(false);
            this.mPayments.setOnClickListener(null);
        }
    }

I even tried to set visibility to Gone from xml file and set it to visible from code however the functionality was same :(
It's probably because I have defined onClick functionality from xml file and my problem would be fixed if I set click listener from code, however, I'm looking for fix the issue in this way.
Any suggestion would be appreciated. Thanks.

A: Try this on FrameLayout like this
  this.frameMain= (FrameLayout) findViewById(R.id.profile_layout);
       if (cachedFeature == null || !cachedFeature.isMade())
        {
            this.mPayments.setVisibility(View.GONE);
            this.mPayments.setClickable(false);
            this.mPayments.setOnClickListener(null);
            this.frameMain.invalidate();
        }

A: After these line:
        this.mPayments.setVisibility(View.GONE);
        this.mPayments.setClickable(false);

Add these lines:
        this.mPayments.setFocusable(false);
        this.mPayments.setFocusableInTouchMode(false);

** EDIT **
Ignore the focusable snippet and try to disable the view like this:
         this.mPayments.setEnabled(false);

You can check if a view can receive click events to make sure everything is rite:
         this.mPayments.isClickable(); // Indicates whether this view reacts to click events or not.

If the above shows false, then it shouldn't react to click events.

A: When you use onClick pattern, you must define a View as parameter on the method implemented in your class.
Maybe you can use a switch with the ID of the view, then check if payments_btn is still visible and fire your action only if is visible.


text:
Q: Django rest fraemwork, как в serializer добавить модель, связную обратной связью(reverse relationships) Здравствуйте у меня такой вопрос, есть 2-е модели.
    class AllProject(models.Model):
        # Preview
        title = models.CharField(verbose_name='Заголовок проекта', max_length=255)
        description = models.TextField(verbose_name='Описание проекта', blank=True)
        img = models.ImageField(verbose_name='Изображение', upload_to=path_image_preview)
        tags =  models.ManyToManyField(AllProjectTags, verbose_name='Тэг', help_text='Тэги используются для фильтрации')
        # Detail
        title_page = models.CharField(verbose_name='Заголовок проекта', max_length=255, blank=True)
        description_page = models.TextField(verbose_name='Описание проекта', blank=True)

        class Meta:
            verbose_name = 'Проект'
            verbose_name_plural = 'Остальные проекты'

        def get_path_name(self):
            return 'all-project'

        def __str__(self):
            return self.title

    class AllProjectImage(models.Model):
        fk = models.ForeignKey(AllProject, related_name='images', on_delete=models.CASCADE)
        image = models.ImageField(upload_to=path_image_gallery,verbose_name='Изображения')

        class Meta:
            verbose_name = 'Изображение'
            verbose_name_plural = 'Галерея'

        def __str__(self):
            return str(self.id)

AllProjectImage используется для хранения картинок и он привязан к AllProject как я понимаю обратной связью.
В admin.py оно подключается так называемым инлайном.
А как такое же сделать с serializer?
class AllProjectImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = AllProjectImage
        fields = '__all__'

class AllProjectSerializer(serializers.ModelSerializer):
    image = AllProjectImageSerializer(many=True)
    class Meta:
        model = AllProject
        fields = '__all__'
        depth = 1

Пи таком serializers.py происходит ошибка:

Как вообще можно получить данные обратно связанной моделью?

A: Почти всё правильно, в AllProjectSerializer замените image = AllProjectImageSerializer(many=True) на images = AllProjectImageSerializer(many=True)
название должно совпадать с related_name для AllProjectImage.
Подробнее тут


text:
Q: Effect Composer in three.js throwing error and not rendering I made two effect composer one for the main screen and one for mini-map view of the whole scene in minified form in top of screen.
I did this:
function postProcessing(renderer) {
    composerScreen = new EffectComposer(renderer)

    // RenderPass is normally placed at the beginning of the chain in order to provide the rendered scene as an input for the next post-processing step.
    const renderPass = new RenderPass(scene, camera)
    // When using post-processing with WebGL, you have to use FXAA for antialiasing
    // Passing { antialias: true } to true when creating WebGLRenderer activates MSAA but only if you render to the default framebuffer
    // (directly to screen).
    const pixelRatio = 1
    let fxaaPass = new ShaderPass(FXAAShader)
    fxaaPass.material.uniforms['resolution'].value.x = 1 / (window.innerWidth * pixelRatio)
    fxaaPass.material.uniforms['resolution'].value.y = 1 / (window.innerHeight * pixelRatio)
    // const copyPass = new ShaderPass(CopyShader)
    // meaning of renderToScreen. I have to set to true only for the 'last' effect
    fxaaPass.renderToScreen = true
    console.log(composerScreen)
    composerScreen.addPass(renderPass)
    composerScreen.addPass(fxaaPass)
    // when screen is resized update fxaa resolution uniform as well

    // The width and height of the THREE.EffectComposer.renderTarget must match that of the WebGLRenderer.
    // #TODO: WHAT? Why? https://stackoverflow.com/questions/16167897/three-js-how-to-add-copyshader-after-fxaashader-r58
    composerMap = new EffectComposer(renderer, renderTarget)
    composerMap.setSize(512, 512)
    let renderPassMap = new RenderPass(scene, mapCamera)
    composerMap.addPass(renderPassMap)
    var effectFXAA_Map = new ShaderPass(FXAAShader)
    effectFXAA_Map.uniforms['resolution'].value.set(1 / 512, 1 / 512)
    composerMap.addPass(effectFXAA_Map)
    const copyPass = new ShaderPass(CopyShader)
    copyPass.renderToScreen = true
    composerMap.addPass(copyPass)
}

and I call
 postProcessing(renderer)

and renderer variable passed in that function is:
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.autoClear = false

and mapCamera is
function initMapCamera() {
    mapCamera = new THREE.OrthographicCamera(left, right, top, bottom, 0.1, 1000)
    // for camera to see down up should be on z axis
    mapCamera.up = new THREE.Vector3(0, 0, -1)
    mapCamera.lookAt(0, 0, 0)
    mapCamera.position.y = 512
    scene.add(mapCamera)
}

my render code is:
function animate(now: number) {
    requestAnimationFrame(animate)
    const delta = now - lastTime
    lastTime = now
    TWEEN.update()
    KeyBoardHandler.keyUpdate(handlers, keys, delta)
    render()
}

function render() {
    renderer.setViewport(0, 0, window.innerWidth, window.innerHeight)
    console.log('composer screen', composerScreen)
    composerScreen.render()
    renderer.clear(false, true, false)
    renderer.setViewport(20, window.innerHeight - 512, 256, 256)
    composerMap.render()
    // controls.update(clock.getDelta())
    // labelRenderer.render(scene, camera)
    // renderer.render(scene, camera)
}

I tried to add all relevant code here and this is the code repo:
https://github.com/pravinpoudel/building-annotation/blob/2bc49e956cd9a4af590aae3b66d4d64d2b9093b4/src/client/client.ts#L150
I have two branches, one is main and another is FPC which have the code with post-processing
It is not able to render anything and it is showing my error:

first one is
console.log(composerScreen)

and when i click on the error in console log

and it goes to composerScreen.render() inside render function


text:
Q: svn resuming aborted checkout Situation - have enormous repository, slow and unreliable link (read - vpn that breaks from time to time).
We are subject of frequent branching, moving things, so every now and then whole new branch should be taken from the repository (checkout).
Is there a way to 'resume' broken checkouts?  Is it safe to do svn checkout with same parameters and expect it to skip what is downloaded and download what is not?

A: Just ran into the same problem.  I had to interrupt a checkout because it was taking an absurdly long time.  When I went to "resume" the checkout, it wasn't clear whether I should re-initiate the checkout or simply do an svn update.
After attempting to to do the svn update to resume the checkout, I got a wonderful error message saying that the directory was "locked".  I tried issuing a "Release Lock" from Tortoise SVN, but this didn't help.
Ultimately, what I ended up having to do was issue an svn cleanup to release whatever stranglehold Subversion had in place.  After that, I was able to continue my previously initiated checkout by performing kicking off another update (svn update or "SVN Update" from the Tortoise SVN context menu).

A: From the Subversion documentation

If you interrupt a checkout (or
  something else interrupts your
  checkout, such as loss of
  connectivity, etc.), you can restart
  it either by issuing the identical
  checkout command again or by updating
  the incomplete working copy.

A: I also had same issue and finally thing which work for me is:-
Step 1. In root folder right click on empty space and select "TortoiseSVN > Clean up..." then check all option in pop-up and run this
Step 2. right click on empty space and click "SVN Update.."
It starts to resume now.

A: svn update

does the job for you.

A: The way I see it, there are three possibilities:

*

*It does the checkout correctly and completely, without any headache for you. Problem solved.

*It checks out everything that didn't get checked out last time. You do 'svn update' and you're golden.

*It discovers that some stuff has been modified since having been checked out, complains, and aborts. You'll just have to remove the conflicting stuff.
In any event, any file that's been successfully checked out of the repository has associated metadata in your local tree and that will ensure that 'svn update' will get you the most recent version.

A: move into the copy directory
svn update
svn cleanup
cd..

svn checkout download_path

A: I had to checkout a big repository over an unreliable connection, so the co failed many times. Based on the answers here, I've ended up with a little loop, trying continuously the checkout (works with bash and other unix shells):
while ! svn co http://myserver/svn/myrepo/
do
    (cd myrepo; svn cleanup)
done

The same with some decoration if you want to know at the end how many retrials were needed:
i=0
while ! svn co http://myserver/svn/myrepo/
do
    i=$[i+1]
    (cd myrepo; svn cleanup)
done
echo $i


text:
Q: PostgreSQL mode in flow test is it possible to use postgresql mode in flow test?
i have try to overwrite datasource.
val nodeConfig = MockNodeConfigOverrides(
                extraDataSourceProperties =
                mapOf("dataSource.url"
                        to "jdbc:h2:mem:partya_persistence;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE")
        )
 nodeA = mockNet.createNode(legalName = CordaX500Name("PartyA", "London", "GB"),configOverrides = nodeConfig)

but error with startup
Unknown data type: "blob"; SQL statement:
CREATE TABLE public.node_info_party_cert (party_name NVARCHAR(255) NOT NULL, ismain BOOLEAN NOT NULL, owning_key_hash NVARCHAR(130), party_cert_binary BLOB) [50004-199] [Failed SQL: CREATE TABLE public.node_info_party_cert (party_name NVARCHAR(255) NOT NULL, ismain BOOLEAN NOT NULL, owning_key_hash NVARCHAR(130), party_cert_binary BLOB)] {changeSet=migration/node-info.changelog-init.xml::1511451595465-11::R3.Corda, databaseChangeLog=master.changelog.json}

A: PostgreSQL mode is not supported in the mock node, but you can use Postgres when using driver test. You can check out documentation about is here.


text:
Q: Probability of squares in set A Question states : Consider set A = {1, 2, 3 ... n}, what's the probability that randomly selected integer from set A is a perfect square?
Thankfully accepting answers.

A: First, let's have a look at how we can find a pattern to get the number of perfect squares in the range $R = 1, 2, 3 ... n$:
Let $k$ be the number of perfect squares in $R$. We need to find $k$.
Difference between consecutive perfect squares is $1 + 2i$, where $i = 1, 2, 3 ... k-1$. Upon subtle observation, you can discover that any perfect square can be written by the following formula:
Perfect Square (PS) = $1+i+2*(1+2+3+ ... i)$, where $i = 1,2,3 ... k-1$
Last perfect square has to be less than or equal to $n$. Therefore, putting $k-1$ in 'PS,' and equating it with $n$, we get
$1+k-1+2*(1+2+3+ ... k-1) <= n$
$\Rightarrow 1+k-1+2*\frac{(k-1)*k}{2} <= n$
$\Rightarrow k+ k^{2} - k <= n$
$\Rightarrow k <= \sqrt{n}$
Since, $k$ has to be positive, I neglected the negative part.
Now, the probability of selecting a perfect square from $R$ = $\frac{\sqrt{n}}{n}$
Note: If you find anything ambiguous, then please let me know in the comments below.

A: Note:
$$
\begin{array}{c|l}
n & \text{# of perfect squares} \\
\hline
1 & 1 \\
2 & 1 \\
3 & 1 \\
4 & 2 \\
5 & 2 \\
\cdot & \cdot \\
8 & 2 \\
9 & 3 \\
10 & 3 \\
\cdot & \cdot \\
15 & 3 \\
16 & 4 \\
\cdot & \cdot \\
n & [\sqrt{n}]
\end{array}
$$
where $[n]$ is the largest integer less than or equal to $n$.
Hence:
$$P(perfect \ square)=\frac{\# \ of \ perfect \ squares}{n}=\frac{[\sqrt{n}]}{n}.$$
For example, if $n=8:$
$$P(perfect \ square) = \frac{[\sqrt{8}]}{8}=\frac{2}{8}=\frac{1}{4}.$$


text:
Q: Soundcloud: What Is going wrong with this Oauth2 request? I have been trying to using oauth2 authentication with an api key.
i'm tracing out every step of the way. Its successfully getting a token, but then giving a 401 error when I try to access https://api.soundcloud/me.
oauth2.RoundTrip: credentials found
 map[
     access_token:1-156891-51311-fec80e6e640f49007
     scope:non-expiring expires_in:0
 ]

oauth2.Get response:
401 Unauthorized 401 HTTP/1.1 1 1
 map[
    Access-Control-Allow-Headers:[Accept, Authorization, Content-Type, Origin]
    Access-Control-Allow-Methods:[GET, PUT, POST, DELETE] Date:[Tue, 27 Oct 2015 02:12:17 GMT] Server:[am/2]
    Access-Control-Allow-Origin:[*]
    Access-Control-Expose-Headers:[Date]
    Cache-Control:[private, max-age=0, must-revalidate private, max-age=0]
    Content-Length:[0]] 0x18d47bc0 0 [] false map[] 0x18d880e0 0x18cbd440
 ]

Does anyone have any insight as to why this might happen? The same problem is not happening with other providers such as github. I am using github.com/stretchr/gomniauth for authentication.


text:
Q: @Font-Face with condensed fonts in the same family I have a number of fonts which fall under the same font family name. I need to generate the @font-face for these fonts
Family Name: Test Pro
Font Name: TestPro-Cond
Font Name: TestPro-CondIt
Font Name: TestPro-It

I understand I can create a @font-face with whatever name I want and reference the font files. However I would like to follow the correct web standard. What I am unsure about is how to handle these 'condensed' fonts. Does anyone have experience with this?
Currently I have
@font-face {
    font-family: "Test Pro Bold Condensed Italic";
    src: url('./fonts/TestPro-BoldCondIt.otf');
    font-weight: normal;
    font-style: normal;
}
@font-face {
    font-family: "Test Pro Bold Italic";
    src: url('./fonts/TestPro-BoldIt.otf');
    font-weight: normal;
    font-style: normal;
}

A: Condensed fonts actually are basically a different family, if you think about it.
What you're doing is fine, but you can simplify the whole tree like this:
@font-face {
    font-family: "Test Pro Condensed";
    src: url('./fonts/TestPro-CondReg.otf');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: "Test Pro Condensed";
    src: url('./fonts/TestPro-BoldCondIt.otf');
    font-weight: bold;
    font-style: italic;
}

@font-face {
    font-family: "Test Pro";
    src: url('./fonts/TestPro-Reg.otf');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: "Test Pro";
    src: url('./fonts/TestPro-BoldIt.otf');
    font-weight: bold;
    font-style: italic;
}

And then only worry about using font-family: "Test Pro"; etc in your styles with the appropriate font-weight and font-style to trigger the heavier weight and/or italic version. The browser will automatically simulate any combinations you don't include (though it may look bad.)
Last thing, try to use woff and woff2 for the src if possible, the file size is much smaller.

A: It should be possible using the css property called font-stretch, but at the time of writing it's not covered in all major browsers.
See https://caniuse.com/#feat=css-font-stretch


text:
Q: My apps crash due to hit backspace in inputfield due to afterTextChanged , how can i handle backspace for this code public void afterTextChanged(Editable editable) {

    String f = y.getText().toString();

    String[] data2 = f.split(" ");

    if (f.substring(f.length() - 1).equals(" ")) {
        StringBuilder M = new StringBuilder();
        String z = y.getText().toString();
        String[] data1 = z.split(" ");
        {
            String last = order(data1[data1.length - 1].toString());

            data1[data1.length - 1] = last.toString();

            for (int i = 0; i < data1.length; i++) {

                M.append(data1[i]);
                M.append(" ");

            }

            y.removeTextChangedListener(this);
            y.setText(M.toString());
            y.setSelection(y.getText().length());
            y.addTextChangedListener(this);

        }
    }
}

this is the code of my afterchangetext in this when the space is detected it changes the previous word to its standard form but when the user write something and trying to remove or hit backspace then apps crash due to this method please elp me how to handle backspace

A: It's crashing while edit text is empty because of using substring method on empty string.
if (f.substring(f.length() - 1).equals(" ")) {
Replace like this:
if (f.length() > 0 && f.substring(f.length() - 1).equals(" ")) {
Let me know if it's having issue.


text:
Q: Amazon S3 Error: The specified bucket exists in another region I'm just setting up a simple splash page basic static HTML and I decided to put it on S3.
my bucket name is called the same as my domain
www.example.com.s3-website.eu-west-2.amazonaws.com/

And then I've got a CNAME set to the same thing.
the only problem is i'm getting a 400 error from Amazon S3
400 Bad Request

  Code: IncorrectEndpoint
  Message: The specified bucket exists in another region. Please direct
  requests to the specified endpoint.

I've checked and my bucket is definitely EU West and this is the endpoint it's given me when serving a static site.

A: You can check your bucket location through the following command.
aws s3api get-bucket-location --bucket {bucketname}

Could it be, that your bucket is located in eu-west-1 instead of eu-west-2?

A: I didn't manage to solve the wrong region problem, however, I created a cloudfront distrubution and set a CNAME to that instead.


text:
Q: Specify Rails Controller Action Based on Domain I have a single application that supports two domains, http://domain1.com and http://domain2.com. Models, controllers and views are shared between the domains.
In the past http://domain1.com/user_type_2/faqs and http://domain2.com/user_type_2/faqs were served up separately using the same controller action. Now, however, for SEO reasons, I want to completely remove the view associated with domain1 and route all user type 2 faq requests (from either domain) to http://domain2.com/user_type_2/faqs - continuing to use the existing controller and actions.
How can I specify a route in routes.rb that redirects all requests from http://domain1.com/user_type_2/faqs to http://domain2.com/user_type_2/faqs?
I've tried
match 'http://domain1.com/user_type_2/faqs', :to => redirect('http://domain2.com/user_type_2/faqs')
and
constraints(:host => /domain1.com/) do
    match "/user_type_2/faqs" => redirect {|params, req| "//domain2.com/#{params[:path]}"}
  end
Neither seems to work.

A: It turns out the answer is a redirect within a domain constraint. Pretty straightforward once I saw it.
constraints domain: 'domain1.com' do
  match 'user_type_2/faqs', :to => redirect('http://domain2.com/user_type_2/faqs')
end


text:
Q: Pass API Text Data to other Page Flutter I'm facing an issue regarding API datas,
I want the pass the texts, Image generated by API to another screen screen
Here is the
      String _name(dynamic user){
    return user['name']['title'];

  }
 String _description(dynamic user){
    return user['name']['description'];
  }

I want to pass these texts to the next screen using Provider or MaterialRoute Page,
How can I do so in a real example
Thanks

A: You can do this by 2 ways:

*

*Pass a data to screen as arguments. For example:

class SecondScreen extends StatelessWidget {
  final String title;
  final String description;

  SecondScreen(this.title, this.description);
}

And in routing:
Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => SecondScreen(title, description)),
);

*Create a model class in Provider and add data to it before moving to another screen and access this data in the second screen.

A Provider basically allows you to access data belonging to class from any widget. Here is a link to the Provider package. You'll find examples over there.


text:
Q: How to rotate/change the orientation of ApplicationWindow QML? I would like to by default set my app at 180 degree orientation.  What is the API to rotate the screen at ApplicationWindow level? I have toolbars and statusbars in my app, so I need to rotate the ApplicationWindow itself.

A: You can use a Page component as main component in your ApplicationWindow
ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Page{
        rotation: 180
        anchors.fill: parent

        footer: ToolBar{ ... }
    }
}

Result:


text:
Q: python pdfplumber: extract pdf with data split into 2 columns I have collection of pdf files which stores information in below format:
Line no 1     Line no. 11
Line no 2     Line no. 12
.             .
.             .
.             .
Line no 10    Line no N

I am using pdfplumber library to extract PDF's text content but, instead of reading from line 1 to 10 at first and then marching towards line 11 (and so on) pdfplumber reads line 1 and line 11 together as a single line. Consider below output:
Line no 1 Line no. 11
Line no 2 Line no. 12
.
.
.

What I expect:
Line no. 1
Line no. 2
.
.
.
Line no. 11
.
.
.

Here is the link to the pdf which I am trying to read.
Glimpse of PDF:

I tried extract_table() utility from pdfplumber library with table settings, but it didn't work (referred answer https://stackoverflow.com/a/63133876/10011503)
Do I need to pass some specific table setting as argument to pdfplumber.open('path_to_pdf').pages[0].extract_table() or is there any other utility and/or workaround?

A: I don't see a table in your PDF section above. I suggest you use the
Page.extract_text(...)

call instead.
The readme from the main documentation has an example of extracting fixed-width text at https://github.com/jsvine/pdfplumber/blob/stable/examples/notebooks/san-jose-pd-firearm-report.ipynb which is more similar to your drug PDF.


text:
Q: How to find child elements of a hidden div using jQuery There is a tab section with two tabs - Tab1 & Tab2.
Each tab pane has elements with class card.
When one tab is active, the other tab pane is set to display:none.

...

...

...

...

...

...

In the above example, the first tab pane is active and the second is hidden.
I would like to find out the number of visible card elements in each pane.
In the browser console, if first tab is active and I execute:
($("#tp1 .card:visible")).length //gives 2  which is correct

($("#tp2 .card:visible")).length //gives 0. It has to be 2

($("#tp2 .card")).length //gives 3. I need only the count of visible elements which is 2

:visible here because some of these are also hidden.
How to get the count of the child elements irrespective of the visibility of the tab pane

A: Give all those hidden card elements a new class

...

...

...

...

...

...

Now you can easily get the number of visible card elements by
($("#tp1 .card")).length - ($("#tp1 .card.invisible")).length

Also the css of your new class will be
.invisible
{ display:none;
}


text:
Q: Update expiration time of a google push notification channel I am currently developing a web API where I need to listen for Google Calendar updates.  I have therefor implemented the google push notifications for PHP following the documentation and everything works fine (Receiving notifications).
The problem I have is that I would like to update the channel expiration time so I don't have to create a new one every time. That is a waste of GPU and API requests, because as the documentation indicates, every time you create a new channel you start with a full initial sync (Synchronize Resources Efficiently) .
Instead, I would like to always make incremental synchronization. Any ideas on how to update the  "expiration" field ?

A: Answer:
You cannot update the channel expiration time, you have to create a new one.
Reference:
From the link you provided, Renewing notification channels:

Currently there is no automatic way to renew a notification channel. When a channel is close to its expiration, you must create a new one by calling the watch method.

Related:

*

*Provide a mechanism to renew activities.watch instead of erroring on non-unique channels


text:
Q: Handling with temporary file stream Say I want to define a TempFileStream class that creates a temporary file using Path.GetTempFileName() method. A temporary file must be deleted when TempFileStream's object is no longer needed, e.g. closed or disposed:
class TempFileStream: FileStream
{
  string m_TempFileName = Path.GetTempFileName();
  public TempFileStream(FileMode fileMode): base(m_TempFileName,fileMode) {}

  /// ...

 public ovverride Dispose(bool disposing)
 {
   /// ???
 }

}

How should I implement this simply and safely?

A: This is an interesting idea, but there's something about this design that troubles me.  Forgive me if you've already addressed this in your design.  But if your design is just a simple wrapper around FileStream, there's a subtle but, I think, significant problem.
If you're deleting the file when the stream is closed, that means that the only way to actually use the data in the file is if the FileAccess is ReadWrite.  Correct?  In other words, you'll be using the file with code that looks like this:
using (TempFileStream t as new TempFileStream())
{
   WriteDataToTempFile(t);
   t.Seek(0, SeekOrigin.Begin);
   ReadDataFromTempFile(t);
}

The problem I see is that ReadDataFromTempFile is expecting the file to be opened for read access, not read/write access.  And this opens the door for some bugs that I think will be very hard to find.  Consider code like this:
using (TempFileStream t as new TempFileStream())
{
   MyClass o = new MyClass(o);
   o.TempStream = t;
   o.ProduceOutput();
   t.Seek(0, SeekOrigin.Begin);
   o.ProcessOutput();
}

...when compared with this:
MyClass o = new MyClass();
string n = Path.GetTempFileName();
using (FileStream s = new FileStream(n, FileMode.Create, FileAccess.Write))
{
   o.TempStream = t;
   o.ProduceOutput();
}
using (FileStream s = new FileStream(n, FileMode.Open, FileAccess.Read))
{
   o.TempStream = t;
   o.ProcessOutput();
}
File.Delete(n);

Sure, the first method is shorter than the second.  But the second method will throw an exception if ProcessOutput calls a method that writes to TempStream.  (Or sets a property whose set accessor raises an event whose event handler dispatches a call to a method that writes to TempStream, which how this problem will probably end up happening.)  The first one will just produce unexpected results for no apparent reason.
You can get around this, I think, by having your TempFileStream class open the underlying FileStream using FileAccess.Write.  Then implement a Rewind method that closes this FileStream and creates a new one that uses FileAccess.Read.  If you do that, any method that tries to write to the file while it's opened for read access (or vice versa) will at least throw an exception.

A: I know this is an older thread, but here's an alternate solution.  I started to implement the TempFileStream, but I wanted more concurrency.  My use-case involves exporting [potentially MBs of] database results to a CSV file via MVC.  I want to begin downloading to the client as soon as data are available from the database query rather than wait for a potentially large temp file to be written before I start downloading.
In this solution, I launch the query in a separate thread which fills an AnonymousPipeStream.  The main thread can then slurp the data from the other end of the pipe as its available.  It uses .Net 4 Tasks.
Hope someone else finds this useful.
-Rob
Controller method:
public FileResult ResultExport ( ReportOptions options )
{
    ResultExport rpt = new ResultExport( options );
    HttpContext.Response.BufferOutput = false;
    return File( rpt.Export(), "text/csv", "results.csv" );
}

Model:
public ResultExport
{
    private AnonymousPipeServerStream WriteStream = null;

    public Stream Export()
    {
        //
        // We'll fire off the database query in a background
        // thread.  It will write data to one end of the pipe.  We'll return the reader
        // end of that pipe to our caller.
        //
        WriteStream = new AnonymousPipeServerStream( PipeDirection.Out );
        AnonymousPipeClientStream reader = new AnonymousPipeClientStream( PipeDirection.In, WriteStream.ClientSafePipeHandle );

        //
        // Call Execute() in a background thread.
        //
        Task.Factory.StartNew( () => Execute() );

        //
        // While Execute() is filling the pipe with data,
        // return the reader end of the pipe to our caller.
        //
        return reader;
    }

    private void Execute ()
    {
        //
        // WriteStream should only by populated by Export()
        //
        if( WriteStream != null )
        {
            using ( StreamWriter sw = new StreamWriter( WriteStream, Encoding.UTF8, 4096 ) )
            {
                //
                // Shove data into the StreamWriter as we get it from the database
                //
                foreach ( string line in ExportCore() )
                {
                    // Each line is a comma-delimited set of values
                    sw.WriteLine( line );
                }
            }
        }
    }
}

A: Try this one instead:
public class TempFileStream : FileStream
{
    public TempFileStream()
        : base(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose) { }
    public TempFileStream(FileAccess access)
        : base(Path.GetTempFileName(), FileMode.Create, access, FileShare.Read, 4096, FileOptions.DeleteOnClose) { }
    public TempFileStream(FileAccess access, FileShare share)
        : base(Path.GetTempFileName(), FileMode.Create, access, share, 4096, FileOptions.DeleteOnClose) { }
    public TempFileStream(FileAccess access, FileShare share, int bufferSize)
        : base(Path.GetTempFileName(), FileMode.Create, access, share, bufferSize, FileOptions.DeleteOnClose) { }
}

The FileOptions.DeleteOnClose option will ensure that the OS deletes the temporary file automatically when you close out the file.  No need for a special Dispose method, because it's all taken care of for you.

A: base.Dispose(disposing); // disposes the base stream so the file is no longer used
if (disposing)
    File.Delete(m_TempFileName); // deletes the file

You should add proper exception handling for File.Delete if you need to.

A: Basically according to TempFileStream logic you always use just created file with unique name (that is what Path.GetTempFileName does) and you always delete it after its use. So there is no need to provide constructor that accepts FileMode as you always use it in the same mode.


text:
Q: How i can find my Drupal version in DB? I am having only the sites folder(except Default Directory) and DB of a website with that how can i find my version.
ACtually in my DB they had fixed the prefix 'd6_' with that i can find it as Drupal6. But i can't find the correct Version of Drupal6.

A: In the info column of your system table in drupal database you can find the serialize text something like ""package";s:4:"Core";s:7:"version";s:4:"7.43";s:4:"core";s:3:"7.x";" of any core modules like aggrigator or block.
when you un-serialize the string you can find the version of drupal
e.g
[version] => 7.43
[core] => 7.x

This is the drupal version 7.43
Thanks

A: I don't think that version is stored somewhere in database, but in files you obviously don't have.
My suggestion is to check versions of all your modules (dir /sites/modules). Every module have version and possible date stored in it's info file. So make a list of release dates of all modules and then find out what was the drupal 6 version at the time your latest module was released and use that version of drupal.


text:
Q: Results of a query not showing up. says "Commands completed successfully" I have a small query that needs print the results in the results pane.
The query runs fine without any errors. But I don't see the output of the query in results pane. All other select statements show the results in the results pane. Just this query is not showing up the results.
In the query option-->Query Results-->SQL sever--> Default destination to "Results to Grid" is already selected.
DECLARE @Start int
SET @Start = 45

WHILE (@Start <=5)
BEGIN
     PRINT CHAR(@Start)
    SET @Start = @Start+1
 END


text:
Q: Where is the error for sending sms from gsm in rasberry? When i run this python code to send sms from gsm, I recive a message

content not supported

import serial
import time

ser = serial.Serial("/dev/ttyAMA0",baudrate=9600)
time.sleep(1)
ser.write('ATE0\r')
time.sleep(1)
ser.write('ATZ\r')
time.sleep(1)
ser.write('AT+CMGF=1\r')
time.sleep(1)
ser.write('AT+CMGS= "+989337282702" \r')
time.sleep(1)
ser.write('hi \r')
time.sleep(1)
ser.write(chr(26))
time.sleep(1)

print 'sent successfully'


text:
Q: OSSRH release not replicating to maven central 3 days ago, I successfully released version 2.0.2 of a maven archetype to OSSRH and it shows up in the OSSRH archetype catalog and can be downloaded from OSS releases (https://oss.sonatype.org/content/repositories/releases/edu/uchicago/mpcs53013/hdfs-ingest-weather-archetype/2.0.2/)
However, if I look in Maven Central, it still shows only version 2.0.1. Shouldn't it be visible after 3 days. Is there a way I can force a sync?
Thanks,
Mike

A: There is:
http://repo1.maven.org/maven2/edu/uchicago/mpcs53013/hdfs-ingest-weather-archetype/2.0.2/
After release to Central Repository by sonatype your artefact should be visible after a few hours:
http://central.sonatype.org/pages/ossrh-guide.html#releasing-to-central
If you have some problem you can check status of sonatype services:
http://status.sonatype.com/
You can also create issue for maven Central Repository:
http://central.sonatype.org/pages/help.html
Mvnrepository is some sort of indexing many maven repository in one place. One of indexing is Central Repository. So if something is wrong with mvnrepository - please contact with support of this site.


text:
Q: Yii2 show image from blob database field I need to display images stored in database blob field inside a div.
There is my Controller
    public function actionQuartos($id)
    {
        $model = new Quarto();
        $quartos = $model::findAll(['hotelId' => $id]);
        return $this->render('quartosDisponiveis', ['quartos'=> $quartos]);
    }

And there is the model
    class Quarto extends \yii\db\ActiveRecord
    {
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'quarto';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['descricao', 'precoNoite', 'estado', 'hotelId'], 'required'],
            [['precoNoite'], 'number'],
            [['estado', 'img'], 'string'],
            [['hotelId'], 'integer'],
            [['descricao'], 'string', 'max' => 150],
            [['hotelId'], 'exist', 'skipOnError' => true, 'targetClass' => Hotel::className(), 'targetAttribute' => ['hotelId' => 'id']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'descricao' => 'Descricao',
            'precoNoite' => 'Preco Noite',
            'estado' => 'Estado',
            'img' => 'Img',
            'hotelId' => 'Hotel ID',
        ];
    }

My view
    <?php

    /* @var $this yii\web\View */

    $this->title = 'TOPHotels';
    ?>

    <?php
    foreach ($quartos as $dado){
    ?>

<?php echo $dado->descricao?>

Preço por noite: <?php echo $dado->precoNoite?>

Comodidades do quarto:

                <?php
                foreach ($dado->comodidadesQuartos as $comodidade){
                    ?>

<?php echo $comodidade->descricao?>

                    <?php
                }
                ?>

            <input type="button"  class="buttonHotel" value="Ver HOTEL"/>

    <?php
    }
    ?>

I want to display images that i uploaded manually, to my view. I Cant figure out what type of code i have to put on my view , or controller, if anyone know please let me know.
I need to display each blob image stored in database in a view, inside a div element.

A: You can use this:
<?= Html::img('data:image/jpeg;base64,'.base64_encode($dado->img), ['alt' => 'My image']) ?>

Also you have to check for your MIME type
image/jpeg for .jpg and .jpeg files
image/png for .png files
image/gif for .gif files


text:
Q: How to do basic DOM manipulation (clear content, append to content) with YUI? I am doing a project with YUI where I attempt to do things I have previously been doing with jQuery. I am finding it difficult to do some basic operations, and namely:

*

*clear content of DOM element

*append to content of DOM element

In jQuery, I would do:
$(".someSelector").empty().append("
something
");

How to do the above in YUI? Seems like it defers to W3C DOM spec in many aspects, I am not very familiar with that spec. If there's any specific W3C or such material I should use, please give specific links.

A: Here is the YUI documentation for Dom methods.
Yahoo! UI Library > dom  > YAHOO.util.Dom
Or try
YAHOO.util.Dom.get("somediv").innerHTML("
something
");

A: YUI does not seem to provide the same level of DOM manipulation that jQuery does (although I haven't played with YUI3 yet, so this may change).
innerHTML definitely works, and was faster once upon a time, although I think this is changing in some modern browsers.  Appending content is easy enough via the standard methods:
element.appendChild(childElement);

Clearing is a little more involved.  I have actually ended up extending the YUI DOM utility and added this as a method:
removeChildren : function(elem)
{
    var theElement = this.get(elem);
    var elemChildren = theElement.childNodes;
    var childCount = elemChildren.length;
    for (var i = childCount -1; i >= 0; i--)
    {
        theElement.removeChild(theElement.childNodes[i]);
    }
}

It's important to note than when looping through the child nodes, I start with the last element and work my way to the front.  This is because whenever a node is removed, the size of the array changes.  Also, if I remove the node at position [0], all the elements of the array move down a position (meaning the element that was at position [1] now becomes the element at position [0]).  If I was to start at the front of the array, I would miss elements, and quickly exceed the array's boundary.


text:
Q: Bring a view on absolute position to front in react native This is happening on with Android and on iOS it's working fine. I have a component that has a badge which I also custom-made.
function HomeMenuCell({ title, imagePath, pressEvent, showBadge, badgeText }) {
    return (
        <TouchableOpacity style={styles.container} onPress={pressEvent}>
            <View style={styles.imageView}>
                <Image source={imagePath} />
            </View>
            <Text style={styles.titleText}>{title}</Text>
            {showBadge && <View style={styles.badgeView}>
                <Text style={styles.badgeText}>{badgeText}</Text>
            </View>}
        </TouchableOpacity>
    );
}

I have a TouchableOpacity component and in this container, I'm doing everything. The badgeView is also positioned based on the container
    container: {
        justifyContent: 'center',
        alignItems: 'center',
        marginBottom: 10,
        marginTop: 10,
        marginRight: 10,
        marginLeft: 20
    },
    badgeView: {
        position: 'absolute',
        backgroundColor: 'pink',
        borderRadius: 8,
        padding: 3,
        // zInndex: 999, //This doesn't work
        right: 0,
        top: 0
    },

But it is hidden behind the imageView
    imageView: {
        width: 50, height: 50,
        shadowOffset: { width: 0, height: 0 },
        shadowColor: 'black',
        shadowOpacity: 0.2,
        elevation: 3,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 8,
    },

I even tried putting those lines of code before. I think it's because the props are not loaded and the view gets rendered. So, any ideas?
Created this quick Snack (Only see in Android): https://snack.expo.io/@chtalha/badge-on-view

A:    badgeView: {
    position: 'absolute',
    backgroundColor: 'red',
    borderRadius: 8,
    padding: 3,
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
    right: -15,
    top: -5
},

Use this style in your badgeView hope this will work for you :)
This this happen because you already use elevation in image so if you wanna display your other view on top of it then you must set higher elevation compare to image view