text:
Q: Can we use one mode for encryption and another for decryption in AES Server side is using AES/ECB/PKCS5Padding mode of encryption and in client side (mobile)is it possible to decrypt it with AES/CBC/PKCS5Padding .or we need to use same mode for both server and client side?
Please advise.

A: ECB and CBC modes are inherently different (wikipedia). ECB simply applies the block cipher on every plaintext block with the key separately, but CBC XORs the current plaintext block with the last ciphertext block.
Exactly the same mode and padding is needed to decrypt in one go. If you have access to AES/CBC/NoPadding, but not AES/ECB/PKCS5Padding or AES/ECB/NoPadding, you can decrypt AES/ECB/PKCS5Padding-encrypted data by decrypting every block separately.
ECB is a mode where every block is encrypted in exactly the same way and not chained with the previous block like in CBC mode. So you can use CBC mode to decrypt every single block separately which results in ECB mode. The IV must be set to 0x00 bytes and the last block must be decrypted with AES/CBC/PKCS5Padding and a zero IV.


text:
Q: Macro substitution in appscript I have a variable sht= "Product" (sheet name)
I have a variable hdr = "Itemcode" (column header)
Now I want to define a new variable with the name "Product_Itemcode" (combination of two other variables) and store the column number in the variable. I could do it by macro substitution (&) earlier, like
&sht_&hdr
How to do it in app script?
My data has many tabs
https://docs.google.com/spreadsheets/d/19Z0Zkx4mBaniD9w9CdrhpB1GRHrkbBHx-FeOy48ax7g/edit?usp=sharing
I want to be able to refer each column by name (not by column number) like
Products[i][Product_Itemcode]
instead of Products[i][0]
This way I can insert new column or delete a column in the tabs without any need to modify the code.
Now I have to find the column number by
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var sheets=ss.getSheets();
  var tsheet=ss.getSheetByName("Product");
  var shtname=tsheet.getName();
  var [hd_Product, ...data_Product] = tsheet.getDataRange().getDisplayValues();

  const Product_Code=hd_product.indexOf('Code');
  const Product_Item=hd_product.indexOf('Item');
  const Product_UOM=hd_product.indexOf('UOM');
  const Product_CAT=hd_product.indexOf('CAT');
  const Product_Price=hd_product.indexOf('Price');
  const Product_Min_Stock=hd_product.indexOf('Min_Stock');
  const Product_Lot=hd_product.indexOf('Lot');
  const Product_Now_Stock=hd_product.indexOf('Now_Stock');
  const Product_Upd_Date=hd_product.indexOf('Upd_Date');
  const Product_Vendor1=hd_product.indexOf('Vendor1');
  const Product_Vendor2=hd_product.indexOf('Vendor2');
  const Product_Vendor3=hd_product.indexOf('Vendor3');

It is time taking to make the code for many tabs (with different names/header names). Can it be automated?

A: *

*You want to create the variables corresponding to the column index of the herders.

*You want to achieve this using Google Apps Script.

In this answer, I would like to propose to use an object for achieving your issue.
Sample script:
function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheets = ss.getSheets();
  const object = sheets.reduce((o, s) => {
    const sheetName = s.getSheetName();
    const headers = s.getRange(1, 1, 1, s.getLastColumn()).getDisplayValues()[0];
    headers.forEach((h, i) => o[`${sheetName}_${h}`] = i);
    return o;
  }, {});
  console.log(object)
}

Result:
When above script is used for your shared Spreadsheet, the following result is retrieved. For example, in this case, object.Product_Code returns 0. So from your question, Products[i][Product_Itemcode] can be written by Products[i][object.Product_Itemcode].
{
  "Product_Code": 0,
  "Product_Item": 1,
  "Product_UOM": 2,
  "Product_CAT": 3,
  "Product_Price": 4,
  "Product_Min_Stock": 5,
  "Product_Lot": 6,
  "Product_Now_Stock": 7,
  "Product_Upd_Date": 8,
  "Product_Vendor1": 9,
  "Product_Vendor2": 10,
  "Product_Vendor3": 11,
  "Vendor_Code": 0,
  "Vendor_Name": 1,
  "Vendor_Credit_Days": 2,
  "Vendor_Mobile": 3,
  "Vendor_Email": 4,
  ,
  ,
  ,

}

Note:

*

*Please use this script with enabling V8.

Reference:

*

*reduce()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I setup XCode 5.1.1 to run iPad2 simulators? I tried downloading old Xcode, but
Things I've tried

*

*Downloading XCode 4.3.3, but it won't run on 10.9.1

*copying XCode 4.3.3 folders into XCode 5.1.1:

*

*iPhoneSimulator5.1.sdk

*iPhoneOS5.1.sdk

A: Technically Xcode 5.1.1 does emulate the iPad 2 - just select "iPad" (without Retina or 64 bit) from the drop down:

Reading between the lines, it looks like you're trying to emulate iOS 5 rather than iPad 2 specifically (which runs iOS 7.x just fine). If that's the case, please note that Mavericks no longer supports the iOS 5 simulator due to Kernel changes. You must run Xcode 5.0 under Mountain Lion for the iOS 5 simulator to work.
This article has further details - perhaps it will help:
http://pinkstone.co.uk/how-to-build-apps-for-ios-5-with-xcode-5/


text:
Q: MySQL replication risks for the master I have a production MySQL server, fairly heavily loaded with an INSERT-only load on one of its databases.  I'd like to attach a non-production (sitting on my desk, more or less) replication slave to it so I can run slow, expensive analysis queries on recently inserted data.
The slave would be outside the regular domain of our DBAs so there is a risk of it going down, running slowly, having an incompatible schema, erroring on replicated statements, etc.  What risks does this pose to the availability and performance of the master?
Given my limited ability to configure the master and complete control over the slave, is there anything I can do to mitigate these risks or shift them towards the (unimportant) slave?

A: If binary logging is already turned on and you are simply creating a new slave, unless you are nearing the limit of network bandwidth on the master (in which case, you have bigger problems), there are really no risks.  From the master's perspective, the slave is just a single client which happens to be grabbing binary logs instead of executing SQL.
If binary logging is not already on the master, this will add to the I/O and storage overhead on the master because each transaction will have to be written to the binary log file after it completes.  This is sequential writes, though, so unless you are already nearing the limits of your I/O subsystem, it shouldn't be a huge deal.


text:
Q: Multi-query match_phrase_prefix elasticsearch I would like to query 2 different prefixes for the same field. The code below works exactly how I would like it to when working with on field:
GET  /logstash-*/_search
{
    "query": {
        "match_phrase_prefix" : {
            "type" : {
                "query" : "job-source"
            }
        }
    }
}

I could not find in the docs how to do this with two queries (I found how to search in multiple fields). I have tried a boolean should and the snippet below but both are not giving me the results I am looking for.
GET  /logstash-*/_search
{
    "query": {
        "match_phrase_prefix" : {
            "type" : {
                "query" : ["job-source","job-find"]
            }
        }
    }
}

How do I query for only documents that have type:job-source or type:job-find as the prefix?
Thank you in advance,

A: You can combine two match_phrase_prefix queries using should and set minimum_should_match to 1.
Sample Query:
{
    "query":
    {
        "bool":
        {
            "should": [
            {
                "match_phrase_prefix":
                {
                    "type": "job-source"
                }
            },
            {
                "match_phrase_prefix":
                {
                    "type": "job-find"
                }
            }],
            "minimum_should_match": 1
        }
    }
}


text:
Q: Drawing per-pixel into a backbuffer or texture to display to screen, using opengl - no glDrawPixels() Basically, I have an array of data (fluid simulation data) which is generated per-frame in real-time from user input (starts in system ram). I want to write the density of the fluid to a texture as an alpha value - I interpolate the array values to result in an array the size of the screen (the grid is relatively small) and map it to a 0 - 255 range. What is the most efficient way (ogl function) to write these values into a texture for use?
Things that have been suggested elsewhere, which I don't think I want to use (please, let me know if I've got it wrong):

*

*glDrawPixels() - I'm under the impression that this will cause an interrupt each time I call it, which would make it slow, particularly at high resolutions.

*Use a shader - I don't think that a shader can accept and process the volume of data in the array each frame (It was mentioned elsewhere that the cap on the amount of data they may accept is too low)

A: If I understand your problem correctly, both solutions are over-complicating the issue. Am I correct in thinking you've already generated an array of size x*y where x and y are your screen resolution, filled with unsigned bytes ?
If so, if you want an OpenGL texture that uses this data as its alpha channel, why not just create a texture, bind it to GL_TEXTURE_2D and call glTexImage2D with your data, using GL_ALPHA as the format and internal format, GL_UNSIGNED_BYTE as the type and (x,y) as the size ?

A: What makes you think a shader would perfom bad? The whole idea of shaders is about processing huge amounts of data very, very fast. Please use Google on the search phrase "General Purpose GPU computing" or "GPGPU".
Shaders can only gather data from buffers, not scatter. But what they can do is change values in the buffers. This allows for a (fragment) shader to write the locations of *GL_POINT*s, which are then in turn placed on the target pixels of the texture. Shader Model 3 and later GPUs can also access texture samplers from the geometry and vertex shader stages, so the fragment shader part gets really simple then.
If you just have a linear stream of positions and values, just send those to OpenGL through a Vertex Array, drawing *GL_POINT*s, with your target texture being a color attachment for a framebuffer object.

A:
What is the most efficient way (ogl function) to write these values into a texture for use?

A good way would be to try to avoid any unnecessary extra copies. So you could use Pixel Buffer Objects which you map to your address space, and use that to directly generate your data into.
Since you want to update this data per frame, you also want to look for efficient buffer object streaming, so that you don't force implicit synchronizations between the CPU and GPU. An easy way to do that in your scenario would be using a ring buffer of 3 PBOs, which you advance every frame.

Things that have been suggested elsewhere, which I don't think I want to use (please, let me know if I've got it wrong):

*

*glDrawPixels() - I'm under the impression that this will cause an interrupt each time I call it, which would make it slow, particularly at high resolutions.

Well, what the driver does is totally implementation-specific. I don't think that the "cause an interrupt each time" is a useful mental image here. You seem to completely underestimate the work the GL implementation will be doing behind your back. A GL call will not correspond to some command which is sent to the GPU.
But not using glDrawPixels is still a good choice. It is not very efficient, and it has been deprecated and removed from modern GL.

*Use a shader - I don't think that a shader can accept and process the volume of data in the array each frame (It was mentioned elsewhere that the cap on the amount of data they may accept is too low)

You got this totally wrong. There is no way to not use a shader. If you're not writing one yourself (e.g. by using old "fixed-function pipeline" of the GL), the GPU driver will provide the shader for you. The hardware implementation for these earlier fixed function stages has been completely superseeded by programmable units - so if you can't do it with shaders, you can't do it with the GPU. And I would strongly recommend to write your own shader (it is the only option in modern GL, anyway).


text:
Q: File names (from multiple files) as a column names in one data frame I have many text files with one column data,different dtype (float64, date), no header inside.
I'm trying to write code which will:
 - get all file names without extension -> create a list (this works!)
 - read all files in one directory and concat them into one data frame with one numerated index.
My code:
filelist = os.listdir(path)                             #Make a file list
file_names=[os.path.splitext(x)[0] for x in filelist]   #Remove file extension

Tried this (first option):
df_list = [pd.read_table(file) for file in filelist]
df = pd.concat(df_list,ignore_index=True)

...but I got 3 columns from 6 files with completely messed data.
Also tried this (second option):
df=pd.DataFrame(columns=file_names)

for file in filelist:
    frame=pd.read_csv(file)
    df=df.append(frame, ignore_index=True)

...this also doesn't work.
Any advice would be appreciated.
Input
At the beginning of Q*.txt files are only zeros (about 100values), and after this numbers shows.
Q1.txt   Q2.txt   T21     T22
  0       0      51.06    77.46
  0       0      50.32    77.33
  0       0      50.90    77.45

When I run "first option", I got:
 filelist
 >>>['Q1.txt', 'Q2.txt','T21.txt', 'T22.txt']
 file_names
 >>>['Q1', 'Q2','T21', 'T22']
 df.dtypes
 >>>0        object
 >>>51.06    object
 >>>77.46    object
 >>>dtype: object

Output file
    0  51.06 77.46
 0  0
 1  0
 2  0

It looks like first 2 files (those with zeros at the beginning) are in one column. Second and third are first values of file T21 and T22.
Thanks to @Viktor Kerkez I've added header=None to the pd.read_table and now all files are in one column, dtype=object.
How can I split all files to many columns ?

A: You can do the next thing:
import os
import pandas as pd

file_names = []
data_frames = []
for filename in os.listdir(path):
    name = os.path.splitext(filename)[0]
    file_names.append(name)
    df = pd.read_csv(filename, header=None)
    df.rename(columns={0: name}, inplace=True)
    data_frames.append(df)

combined = pd.concat(data_frames, axis=1)

Here I renamed every DataFrame column to match the file name, you can leave that step out, and just use ignore_index=True.


text:
Q: Jaxb2-annotate-plugin does not work with episodes I am trying to enforce enum validation for my generated JAXB classes, but I am having some issues with getting them bound.
The basic XSD setup is:
-enumsXSD
-2 other XSDs that import this XSD

To provent duplication of my classes I am using episodes, but it looks like this does not play nice when adding annotions in the enumsXSD
com.sun.istack.SAXParseException2: compiler was unable to honor this annox:annotateEnumValueMethod customization. It is attached to a wrong place, or its inconsistent with other bindings.

[ERROR] Error while generating code.Location [ file:somewhere/generic.episode{64,99}].
com.sun.istack.SAXParseException2: (the above customization is attached to the following location in the schema)

The code:
<plugins>
      <plugin>
        <groupId>org.jvnet.jaxb2.maven2</groupId>
        <artifactId>maven-jaxb2-plugin</artifactId>
        <version>0.13.3</version>
        <configuration>
          <extension>true</extension>
          <args>
            <arg>-Xannotate</arg>
          </args>
          <plugins>
            <plugin>
              <groupId>org.jvnet.jaxb2_commons</groupId>
              <artifactId>jaxb2-basics-annotate</artifactId>
              <version>1.0.4</version>
            </plugin>
          </plugins>
        </configuration>
        <executions>
          <!--GENERIC ENUMS -->
          <execution>
            <id>ENUMS</id>
            <goals>
              <goal>generate</goal>
            </goals>
            <configuration>
              <extension>true</extension>
            <generatePackage>com.foo.generic.enums</generatePackage>
              <generateDirectory>${project.build.directory}/generated-sources/xjc1/generic</generateDirectory>
              <!-- Define the directory where we should find the XSD files -->
              <schemaDirectory>
                src/main/resources/dtd/generic
              </schemaDirectory>
              <schemaIncludes>
                <source>enums.xsd</source>
              </schemaIncludes>
              <episodeFile>
                ${project.build.directory}/generated-sources/xjc1/generic/META-INF/generic.episode
              </episodeFile>
            </configuration>
          </execution>
          <execution>
            <id>A_XSD</id>
            <goals>
              <goal>generate</goal>
            </goals>
            <configuration>
              <extension>true</extension>
              <bindingDirectory>${project.build.directory}/generated-sources/xjc1/generic/META-INF</bindingDirectory>
              <bindingIncludes>
                <include>generic.episode</include>
              </bindingIncludes>

              <!-- Set the package of the generated code -->
              <generatePackage>com.foo.something</generatePackage>
              <generateDirectory>${project.build.directory}/generated-sources/xjc1/a_something</generateDirectory>

              <!-- Define the directory where we should find the XSD files -->
              <schemaDirectory>
                src/main/resources/dtd/someplace/a/
              </schemaDirectory>
              <schemaIncludes>
                <source>*.xsd</source>
              </schemaIncludes>
            </configuration>
          </execution>
     </executions>
   <plugin>
</plugins>

And in the enums XSD
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema elementFormDefault="qualified" id="commonEnums"
           targetNamespace="http://foo.com/xsd/commons/enum"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
           jaxb:version="2.1"
           xmlns:annox="http://annox.dev.java.net"
           jaxb:extensionBindingPrefixes="annox">
<xs:simpleType name="bulletinCategory">
    <xs:annotation>
      <xs:appinfo>
        <annox:annotateEnumValueMethod>@java.lang.Deprecated</annox:annotateEnumValueMethod>
      </xs:appinfo>
    </xs:annotation>
    <xs:restriction base="xs:string">
      <xs:enumeration value="valueA" />
      <xs:enumeration value="valueB" />
      <xs:enumeration value="valueC" />
    </xs:restriction>
  </xs:simpleType>
</xs>

Ideally speaking the @deprecated should be @XmlJavaTypeAdapter(FooAdapter.class) but I thought let's start small.

A: The problem is probably that you've included customizations directly into the enums.xsd. So when you compile other schemas, these customizations are considered as well.
But since you also seem to use the enums.xsd as episode, this effectively prevents generation of enum classes. With no enum classes, customizations cannot be applied so they are not marked as "recognized" and this produces the error you get.
To solve this, when compiling enums.xsd, simply move customizations into a separate bindings file and use it during compilation.
Then, when compiling other schemas, use enums.xsd as episode but do not use that bindings file with customizations for enums.xsd.


text:
Q: Installing feature in wso2 apim How do i install Logging management feature in wso2 apim version-3.1.1 using pom file.
I tried from official doc in below link:
https://docs.wso2.com/m/mobile.action#page/85376969
But I'm facing dependency conflict.


text:
Q: Problem with spaces in a filepath - commandline execution in C# I am building a gui for a commandline program.
In txtBoxUrls[TextBox] file paths are entered line by line.
If the file path contains spaces the program is not working properly.
The program is given below.
string[] urls = txtBoxUrls.Text.ToString().Split(new char[] { '\n', '\r' });

string s1;
string text;
foreach (string s in urls)
{
    if (s.Contains(" "))
    {
        s1 = @"""" + s + @"""";
        text += s1 + " ";
    }
    else
    {
        text += s + " ";
    }
}

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.CreateNoWindow = true;

proc.StartInfo.FileName = @"wk.exe";

proc.StartInfo.Arguments = text + " " + txtFileName.Text;

proc.StartInfo.UseShellExecute = false;

proc.StartInfo.RedirectStandardOutput = true;

proc.Start();

//Get program output
string strOutput = proc.StandardOutput.ReadToEnd();

//Wait for process to finish
proc.WaitForExit();

For example if the file path entered in txtBoxUrls is "C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm", The program will not work. This file path with double quotes will work in the windows command line(I am not using the GUI) nicely.
What would be the solution.

A: Usually to get around spaces in filenames, you'll need to wrap your argument in double quotes. If you leave out the quotes the program will think it has two arguments. Something like this...
wk.exe "C:\VS2008\Projects\web2pdf\web2pdf\bin\Release\Test Page.htm"

Also, this line appears to have too many quotes. Four, instead of three:
s1 = @"""" + s + @"""";

A: proc.StartInfo.Arguments = text + " " + txtBoxUrls.Text + " " + txtFileName.Text;

In this line, text already contains the properly quoted version of your txtBoxUrls strings. Why do you add them again in unquoted form (+ txtBoxUrls.Text)? If I understood your code corrently, the following should work:
proc.StartInfo.Arguments = text + " " + txtFileName.Text;

In fact, since txtFileName.Text could probably contain spaces, you should quote it as well, just to be sure:
proc.StartInfo.Arguments = text + " \"" + txtFileName.Text + "\"";

(or, using your syntax:)
proc.StartInfo.Arguments = text + @" """ + txtFileName.Text + @"""";

A: Take a look at the Path class - http://msdn.microsoft.com/en-us/library/system.io.path.aspx
Path.combine might be what you are looking for.


text:
Q: Force bubbles to left in D3.js I am trying in many ways to create a bubble chart by forcing the left of the page based on the value. The highest value bubble should be in the upper left corner. As other approaches didn't work, I looked for an example in which the bubbles are forcing to the center of the page and now I'm trying to adjust to the left, the result I need is the same as the example image above.

My code:
function bubbleChart() {

var width = 940;
var height = 600;

var center = {
    x: width / 2,
    y: height / 2
};
var left = {
    x: 0,
    y: 300
};

var forceStrength = 0.03;

var svg = null;
var bubbles = null;
var nodes = [];

function charge(d) {
    return -Math.pow(d.radius, 2.0) * forceStrength;
}

var simulation = d3.forceSimulation()
    .velocityDecay(0.2)
    .force('x', d3.forceX().strength(forceStrength).x(left.x))
    .force('y', d3.forceY().strength(forceStrength).y(left.y))
    .force('charge', d3.forceManyBody().strength(charge))
    .on('tick', ticked);

simulation.stop();

var fillColor = d3.scaleOrdinal()
    .domain(['low', 'medium', 'high'])
    .range(['#d84b2a', '#beccae', '#7aa25c']);

function createNodes(rawData) {

    var maxAmount = d3.max(rawData, function(d) {
        return +d.total_amount;
    });

    var radiusScale = d3.scalePow()
        .exponent(0.5)
        .range([2, 85])
        .domain([0, maxAmount]);

    var myNodes = rawData.map(function(d) {
        return {
            id: d.id,
            radius: radiusScale(+d.total_amount),
            value: +d.total_amount,
            name: d.grant_title,
            org: d.organization,
            group: d.group,
            year: d.start_year,
            x: Math.random() * 900,
            y: Math.random() * 800
        };
    });

    myNodes.sort(function(a, b) {
        return b.value - a.value;
    });

    return myNodes;
}

var chart = function chart(selector, rawData) {

    nodes = createNodes(rawData);

    svg = d3.select(selector)
        .append('svg')
        .attr('width', width)
        .attr('height', height);

    bubbles = svg.selectAll('.bubble')
        .data(nodes, function(d) {
            return d.id;
        });

    var bubblesE = bubbles.enter().append('circle')
        .classed('bubble', true)
        .attr('r', 0)
        .attr('fill', function(d) {
            return fillColor(d.group);
        })
        .attr('stroke', function(d) {
            return d3.rgb(fillColor(d.group)).darker();
        })
        .attr('stroke-width', 2)
        .on('mouseover', showDetail)
        .on('mouseout', hideDetail);

    bubbles = bubbles.merge(bubblesE);

    bubbles.transition()
        .duration(2000)
        .attr('r', function(d) {
            return d.radius;
        });

    simulation.nodes(nodes);

    groupBubbles();
};

function ticked() {
    bubbles
        .attr('cx', function(d) {
            return d.x;
        })
        .attr('cy', function(d) {
            return d.y;
        });
}

function nodeYearPos(d) {
    return yearCenters[d.year].x;
}

function groupBubbles() {
    hideYearTitles();

    // @v4 Reset the 'x' force to draw the bubbles to the center.
    simulation.force('x', d3.forceX().strength(forceStrength).x(center.x));

    // @v4 We can reset the alpha value and restart the simulation
    simulation.alpha(1).restart();
}

function splitBubbles() {
    showYearTitles();

    // @v4 Reset the 'x' force to draw the bubbles to their year centers
    simulation.force('x', d3.forceX().strength(forceStrength).x(nodeYearPos));

    // @v4 We can reset the alpha value and restart the simulation
    simulation.alpha(1).restart();
}

function hideYearTitles() {
    svg.selectAll('.year').remove();
}

function showYearTitles() {
    // Another way to do this would be to create
    // the year texts once and then just hide them.
    var yearsData = d3.keys(yearsTitleX);
    var years = svg.selectAll('.year')
        .data(yearsData);

    years.enter().append('text')
        .attr('class', 'year')
        .attr('x', function(d) {
            return yearsTitleX[d];
        })
        .attr('y', 40)
        .attr('text-anchor', 'middle')
        .text(function(d) {
            return d;
        });
}

function showDetail(d) {
    // change outline to indicate hover state.
    d3.select(this).attr('stroke', 'black');

    var content = '';

    tooltip.showTooltip(content, d3.event);
}

function hideDetail(d) {
    // reset outline
    d3.select(this)
        .attr('stroke', d3.rgb(fillColor(d.group)).darker());

    tooltip.hideTooltip();
}

This is my complete code on Vizhub:
https://vizhub.com/barbosa-renan/2864204410d54af5a5c402cdfdd9959d?edit=files&file=index.js
Note:
In other attempts I tried to use .domain () and .range but in this scenario it didn't work because when I have bubbles with a very high value and others with a very low value they are very distant.


text:
Q: Using Resource File with PrivateFontCollection I'm using the PrivateFontCollection class in a c++ program, with a .ttf file in the "Resource Files" folder.  I would like to be able to do something along the lines of this:
privateFontCollection.AddFontFile(L"Exo-Regular.ttf");

But the only way I can seem to get to it working is by accessing it through a local file path, like this:
privateFontCollection.AddFontFile(L"C:\\Users\\maybe\\Desktop\\Exo-Regular.ttf");

A: You can't do this with the AddFontFile() method; the path string it expects cannot resolve into the resources embedded in your compiled program.
Instead, you will have to use AddMemoryFont()...and pass it a pointer to resource data you've fetched via resource-aware APIs.
There's a question from 2013 with someone doing this in C#: "addFontFile from resources".  I don't know what other class libraries you are using, but if you were programming to straight Win32, getting a pointer and size for your font would look something like this:
HMODULE module = NULL; // search current process, override if needed
HRSRC resource = FindResource(module, L"Exo-Regular.ttf", RT_RCDATA);
if (!resource) {...error handling... }
HGLOBAL handle = LoadResource(module, resource);
if (!handle) {...error handling... }

// "It is not necessary to unlock resources because the system
// automatically deletes them when the process that created
// them terminates."
//
void *memory = LockResource(handle);
DWORD length = SizeofResource(module, resource);

privateFontCollection.AddMemoryFont(memory, length);


text:
Q: I cannot retrieve json data from php with Angular $http.get This my php code
    <?php

try {
    $dbcon=new PDO('mysql:host=localhost;dbname=angular;charset=utf8',"root","");

    $dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbcon->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
    $query="SELECT * FROM products ";
    $sql=$dbcon->prepare($query);
    $sql->execute();
    $result=$sql->fetchAll(PDO::FETCH_OBJ);

    $json_result=json_encode($result);

    echo $json_result;

}catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

?>

and this my controller to angular
  function ProductListCtrl($http)
{

    $http.get('api/products.php').success(function (data) { alert(data); this.product = data; });

}

the alert message is [object Object,...] ,how can i retrieve the json data from php?

A: $http.get work fine with JSON
I recommend you to validate your json and test again
I created a simple example for you with $http and ng-repeat
<!doctype html>

{{item.name}}

and the json file is
[{
  "name":"name1"
},
{
  "name":"name2"
}]

and also a link to watch it live in Plunker
http://plnkr.co/edit/MN6UPg1ba1OYNFNHKMdG?p=preview

A: I solved the problem.The wrong is with this.product
(function ()
{
    "use strict";
   var app = angular.module('ProductList');
   app.controller('ProductListCtrl',['$scope','$http', ProductListCtrl]);

   function ProductListCtrl($scope, $http) {

       $http.get('api/products.php').success(function (data) { $scope.product = data; });

   }

}());


text:
Q: Registry Restore programmatically in vb.net I want to compare all registry values to another .reg file or a .txt file and make desired changes in the system registry...
How to do this in vb.net ?

A: What you're looking for is My.Computer.Registry - see http://msdn.microsoft.com/en-us/library/sykcb9xf%28v=VS.90%29.aspx for details.  Also, save and load value from registry in vb.net and Change a registry value in VB.NET have some very good information.


text:
Q: Делать onBlur при нажатии Enter Как сделать, чтобы убирался фокус у поля ввода при нажатии клавиши Enter?
import React, {useState} from 'react';

const TodoInput = (props) => {
   const defaulTitle = 'Здесь будет ваша задача';

   const [todoString, setTodoString] = useState('');
   const [inputValue, setInputValue] = useState('');

   const handleOnBlurInputTitle = (evt) => {
      const { value } = evt.target;
      if (value.trim()){
         setTodoString(value);
         setInputValue('');
         return;
      }
      setTodoString(defaulTitle);
   };

   const handleOnChangeInputTitle = (evt) => setInputValue( evt.target.value);

   return (

{todoString || defaulTitle}

            <input
               type="text"
               id="title"
               value={inputValue}
               onBlur={handleOnBlurInputTitle}
               onChange={handleOnChangeInputTitle}
            />
            Введите название задачи

   )
};

export default TodoInput;

A: onKeyDown: ev => ev.key === 'Enter' && ev.target.blur()

const {useState} = React
const e = React.createElement
const App = (props) => {
   const defaulTitle = 'Здесь будет ваша задача';

   const [todoString, setTodoString] = useState('');
   const [inputValue, setInputValue] = useState('');

   const handleOnBlurInputTitle = (evt) => {
      const { value } = evt.target;
      if (value.trim()){
         setTodoString(value);
         setInputValue('');
         return;
      }
      setTodoString(defaulTitle);
   };

   const handleOnChangeInputTitle = (evt) => setInputValue( evt.target.value);

   return [
     e("input",{
       key: "inp",
       type: "text",
       value: inputValue,
       onBlur: handleOnBlurInputTitle,
       onChange: handleOnChangeInputTitle,
       onKeyDown: ev => ev.key === 'Enter' && ev.target.blur()
     }),
     e("div",{key: "res", tabIndex: 1}, todoString || defaulTitle)
   ]
};
const container = document.createElement("div")
document.body.appendChild(container)
ReactDOM.render(e(App),container)


text:
Q: Specific user display name by id with shortcode? I have been trying several combinations for displaying the display name for a specific user by ID in WordPress, but in the end, I couldn't make it work. I need help, please. The code I'm trying to use is the following:

function custom_id_display_name($atts, $content = null) {

   extract( shortcode_atts(
           array('id' => '0',), $atts
                          )
           );

 /*  return $display_name( $user_id, 96 ); // display the specific user_id's name*/
   return get_display_name($atts['id'], 96);
}

add_shortcode('custom_display_name','custom_id_display_name');

The "funny" thing is that the code worked well for custom avatar with a different return,
 return get_avatar($atts['id'], 96);

so I have no idea why it's not working for the display name. Thanks for your help! :-)

A: You can use get_user_by( string $field, int|string $value ) get_user_by here is the stackoverflow referance

A: First you get the user object.
$user = get_user_by( 'ID', $user_id );

Then display name you get with:
$display_name = $user->display_name;


text:
Q: Column length change on SQL Server 2005 I changed field length named 'State'  from nvarchar(1) to nvarchar(10).
Works properly on Server side.
But on client side (I use Delphi7 and connect with Adoquery) there is a problem after insert a record.
Client send 'Active' text to server but on server side it seems at table only 'A' character, not 'Active'.
Could anyone help ?

A: You will have to change the property Size of your published field State to 10.
If you are sending data per parameterized queries you will have to adapt the Size of the parameters.


text:
Q: How to add sort,limit and skip in the aggregate query shown below? This is my data structure
{
    "_id" : ObjectId("57f37f18517f72bc09ee7632"),
    "name" : "testdata",
    "createdBy" : "57f1fdef1d3c40141617d215",

    "transitionEnabled" : false,
    "status" : "active",
    "createdDateTime" : ISODate("2016-10-04T10:06:16.195Z"),
    "accounts" : [
        "57f37f75517f72bc09ee7634"
    ],
    "deliverables" : [],
    "risks" : [],
    "issues" : {
        "_id" : ObjectId("57f38398517f72bc09ee7680"),
        "title" : "test",
        "description" : "Delay in testing due to issues with Provider Finder dataload in the test region. This has impacted the production release planned for Sep 30th",
        "plannedStartDate" : ISODate("2016-09-01T00:00:00.000Z"),
        "plannedEndDate" : ISODate("2016-10-30T00:00:00.000Z"),
        "assignedTo" : "57f375ea517f72bc09ee762a",
        "createdBy" : ObjectId("57f375ea517f72bc09ee762a"),
        "likes" : 0,
        "createdDateTime" : ISODate("2016-10-04T10:25:28.301Z"),
        "status" : "open",
        "stakeholders" : [],
        "__v" : 0,
        "lastUpdatedTime" : ISODate("2019-11-15T09:19:06.279Z")
    },
    "__v" : 0
}

I would like to select all the issues group by the organization and I want to implement sort,limit and skip for those data(the sub array issues data only from the above). For that I've tried the following code
db.organizations.aggregate([
    {
        "$lookup" : {
            "from" : "issues",
            "localField" : "issues.str",
            "foreignField" : "_id.str",
            "as" : "issues"
        }
    },
    {$sort: {weight: -1, "issues.lastUpdatedTime": 1}}
    {
       $group:
         {
           _id: "$issues",
         },
     },
])
I am getting the result as follows.
How to sort and set limit and skip for the below query? Results returned by the query is also attached.
But I not need the outer _id field which shown in the above result. Please help me to solve this problem.

A: Your sort not working for field issues.lastUpdatedTime because issues is an array of object after $lookup just not a plain object. so you need to $unwind first then apply sort
After sort you should use skip and limit. like
{$unwind:"$issues"},
{$sort: {weight: -1, "issues.lastUpdatedTime": 1}},
{ $skip: 10 },// set value as you need
{ $limit : 50 }// set value as you need

NB: $limit always should be after $skip for aggregation. so code will be like
db.organizations.aggregate([
  {
    "$lookup": { "from": "issues", "localField": "issues.str", "foreignField": "_id.str", "as": "issues" }
  },
  {$unwind:"$issues"},
  {$sort: {weight: -1, "issues.lastUpdatedTime": 1}},
  {$skip: 10},
  {$limit: 50}
]);

NB: If you want to return fixed amount of document after grouping then you should use $skip and $limit anfter $group stage

A: first $unwind the issues sub array and using its result its possible to apply sort, skip and limit


text:
Q: select disappears with onmouseenter I want create a menubar. when mouse is over a menu, a div appairs.

            FIND

The DIV that will be appears is moved where in place of comment via .appendTo jQuery function.
This is the div that appears:

   TITLE
   <select class="jmenu noProp">
   <option>1M</option>
   <option>3M</option>
   <option>5M</option>
   </select>
   FIND <input> </input>
   <button>GO</button>

I have binded the event in this way:
$(document).ready(function(){
   $('li.jmenu').mouseenter(jMenu.showMenu);
   $('li.jmenu').mouseleave(jMenu.leaveTabs);
        });

where showMenu and leaveTabs are function that show or hide the div.
It works fine, but when I click on select the option of select and disappears.
Any suggestions?
Thanks


text:
Q: Python: Pandas replace with regex I am trying to replace the data using Pandas.
Following is my aim -

*

*Remove alphabets from temperature and windspeed columns. 32 F
will be replaced by 32 and 6 mph will be replaced by 6.

*Convert all negative numbers in temperature and windspeed to
NaN. -99999 will be converted to NaN.

*Convert all 0 in event to No Event
Following is my code
import pandas as pd
import numpy as np
input_data = {'day': ['1/1/2017', '1/4/2017', '1/5/2017', '1/6/2017',
                         '1/7/2017', '1/8/2017', '1/9/2017', '1/10/2017', '1/11/2017'],
             'temperature': ['32 F', -99999, 28, -99999, '32 C', '38 F', 35, 34, 40],
             'windspeed': ['6 mph', 9, -99999, 7, -88888, -99999, '10 kmph', 8, 12],
             'event': ['Rain', 'Sunny', 'Snow', 0, 'Rain', 'Sunny', 0, 'Cloudy', 'Sunny']
      }
weather2 = pd.DataFrame(input_data)
new_weather = weather2.replace({"temperature":{-99999: np.NaN,
                                          -88888: np.NaN,
                                          '[A-Za-z]':''},
                            "windspeed":{-99999: np.NaN,
                                          -88888: np.NaN,
                                          '[A-Za-z]':''},
                            "event":{0:'No Event'}},regex=True)

The output is as follows -

Only regex is changed. How can I combine regex with other replace?

A: Since in the beginning your column type should be string , all the number here should be string type
new_weather = weather2.replace({"temperature":{'-99999': np.NaN,
                                          '-88888': np.NaN,
                                          '[A-Za-z]':''},
                            "windspeed":{'-99999': np.NaN,
                                          '-88888': np.NaN,
                                          '[A-Za-z]':''},
                            "event":{'0':'No Event'}},regex=True)

If you want to know more information , try
weather2.applymap(type)


text:
Q: hibernate - making type of column in mysql only date and not datetime I am storing date in mysql database using field of type DATE :
@Temporal(TemporalType.DATE)
@Column(name="RECIEVING_DATE")
private Date recieving_date;

// getters and setters

but when hibernate saves it , date is saved in type of datetime format, i.e. it doesn't store just 2015-02-23 but 2015-02-23 00:00:00.
The code I am using for inserting the date
String recieving_date = request.getParameter("recieving_date");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    java.sql.Date ds = null;
    try {
        Date date = df.parse(recieving_date);
        ds=new java.sql.Date(date.getTime());
    } catch (ParseException e1) {
        System.out.println("Exception occured in parsing date : "+e1);
    }
    doc_mvmnt.setRecieving_date(ds);

Now , I can change type by running alter table query myself in database , but that will be painful every time. How can I tell hibernate to keep the type I want . And further , if this is possible , is it possible to define the size of varchar and integers using hibernate. Please help

A: as I see you are passing only date part of datetime to the recieving_date and surely the type of recieving_date is java.sql.Date (as you passing date of that type to it) so I think one of these annotations should work @Type(type="date") or @Temporal(TemporalType.DATE) and as the second one does not work try the other and give a feedback:
@Column(name="RECIEVING_DATE")
@Type(type="date")
private Date recieving_date;

// getters and setters

if this does not solve the issue then try with modifying the getters and setters for your custom format


text:
Q: Android-AltBeacon-library intergration in a java class I'm trying to integrate the altbeacon function in a java class in android studio, but I'm getting an error because of the getActivity. I want to created an object from this class in onahter Activities..
so any idea how could it work?
It works perfect, when I add the altbeacon class in a activity under protected void onCreate(Bundle savedInstanceState).
public class detectRoom  implements BeaconConsumer {

    private List <IBeaconSensor> beaconList = new ArrayList <IBeaconSensor> ();

    private BeaconManager beaconManager;

    public detectRoom() {
     name="detectRoom";
    }
    private String detectRoomName(String raum) {
        return raum;
    }

    public void detectRoomMet () {

        for (int i = 0;i< beaconList.size() ;i++){

            if(beaconList.get(i).getName().equals("45")) {    // 6 = Minor of Ibeacon
                detectRoomName("Room3");

            }

            if(beaconList.get(i).getName().equals("55")) {
                detectRoomName("Room2");

            }

            if(beaconList.get(i).getName().equals("85")) {
                detectRoomName("Room1");

            }

            else {
                detectRoomName("UnknowRoom");

            }

        }
    }

    @Override
    public void onBeaconServiceConnect() {

        beaconManager = new BeaconManager(getApplicationContext());
        beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
        this.beaconManager.setRangeNotifier(new RangeNotifier() {
            @Override
            public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
                if (beacons.size() > 0) {
                    beaconList.clear();
                    for(Iterator<Beacon> iterator = beacons.iterator(); iterator.hasNext();) {

                        beaconList.add(new IBeaconSensor (iterator.next().getId3().toString()));
                    }

                }
            }
        });
        try {
            this.beaconManager.startRangingBeaconsInRegion(new Region("MyRegionId", null, null, null));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Context getApplicationContext() {
        return null;
    }

    @Override
    public void unbindService(ServiceConnection serviceConnection) {
        this.beaconManager.unbind(this);
    }

    @Override
    public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
        return false;
    }

    public void bindBeacon() {
        beaconManager.bind(this);
    }

    public void unBindBeacon() {
        beaconManager.unbind(this);
    }
}

A: When making a POJO that extends BeaconConsumer you must do two things:

*

*Pass a reference to an Android Context to the POJO.

*Chain the methods bindService, unbindService, getApplicationContext to the Context above.

Like this:
public class Pojo extends BeaconConsumer() {
    private Context mContext;
    public Pojo(Context context) {
      mContext = context;
    }
    @Override
    public Context getApplicationContext() {
        return mContext.getApplicationContext();
    }

    @Override
    public void unbindService(ServiceConnection serviceConnection) {
        mContext.unbindService(serviceConnection);
    }

    @Override
    public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
        return mContext.bindService(intent, serviceConnection, i);
    }

    ...

}


text:
Q: VS2015: Variadic template specialization This code
#include <iostream>
#include <type_traits>

template<typename Head, typename... Tail>
struct Is_Admitted {
    constexpr static bool value = Is_Admitted<Head>::value && Is_Admitted<Tail...>::value;
};

template<>
template<typename T>
struct Is_Admitted<T> : public std::false_type{};

template<> struct Is_Admitted<int> : public std::true_type{};
template<> struct Is_Admitted<double> : public std::true_type{};

int main()
{
    std::cout << Is_Admitted<int, double>::value << '\n';
    std::cout << Is_Admitted<int, char>::value << '\n';
}

*

*compiles and run fine under GCC (>=4.7, with c++11, c++14 or c++17 support enabled)

*compiles with a warning and run fine with clang 3.6 (with c++11, c++14 or c++17 support enabled)

*does not compile under VS2015RC (or Preview) with the following errors:

(error descriptions are translated in English by myself as I was not able to set English as compiler language, so they might mismatch with original ones)
error C2910: 'Is_Admitted<T,>': impossible to perform explicit specialization
error C2065: 'value': undeclared identifier
error C2976: 'Is_Admitted': insufficients template arguments
error C2131: constant expression does not return any value

Which compiler is right and which one is wrong? Is that code compliant to either c++11, c++14 or c++17 standard?
And what is the right way to do what I'm trying to do, that is a variadic type function that returns true only if all template type parameters are of some admitted types?

A: You have an extra template<> here:
template<>   // <===
template<typename T>
struct Is_Admitted<T> : public std::false_type{};

Your code gives me the same error via webcompiler.
Simply remove it and it compiles fine. I do not understand how this compiles on either gcc or clang.
Two template  declarations are only necessary when you're defining a member template of a class template outside of the class definition, e.g.:
template <typename T>
struct Foo {
    template <typename U>
    void bar();
};

template <typename T>
template <typename U>
void Foo<T>::bar() { ... }


text:
Q: воспроизведение gif только при помощи javascript здравствуйте, вообщем хочу сделать воспроизведение гиф, думаю всем понятно о чем идет речь, есть статическая картинка, на ней иконка Play и при нажатии src меняется на гифку. я знаю как это сделать на php+js создавая заранее статичное изображение, но хотел бы узнать можно ли сделать это на чистом js/jq имя только gif картинку? чтобы не создавать каждый раз на пыхе jpeg изображение

A: Если хотите purejs-решение, пожалуйста. Надеюсь вы не расчитывали что оно будет простым. В данном случае я использовал библиотеку gif-frames, но её работа (на клиенте?) приводит к артефактам.
Ну и на последок снова прочту вам Отче наш: Никто не занимается такими вещами на клиенте и причин тому несколько:

*

*Потребность писать кроссбраузерный скрипт т.к. браузеров множество, как и клиентских реализаций JavaScript. Добиться работоспособности такого кода на всех и вся будет проблематично.

*Клиент будет выполнять этот код каждый раз при загрузке страницы.

*Трафик: клиент будет качать тяжелый gif-файл, только для того что бы увидеть его превью. Для мобильных устройств это веский аргумент.

*Высока вероятность "повесить" пользовательский клиент на таких вычислениях.

*Сервер проделает эту операцию один раз и закеширует результат. Далее клиент будет качать это превью и, только при необходимости, весь gif.

var $file = document.querySelector('#file'),
    $frames = document.querySelector('#frames'),
    $type = document.querySelector('#type'),
    $output = document.querySelector('.output'),
    $extract = document.querySelector('#extract');

/**
 * Конвертирует тип File в строку base64
 * @see https://ru.wikipedia.org/wiki/Base64
 * @param {File} file
 * @param {Function} callback
 */
function fileToBase64(file, callback) {
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function onload() { callback(reader.result); };
  reader.onerror = function onerror(error) { alert('Error: ', error); };
}

/**
 * Извлечёт указанные кадры
 * @param {File} file Файл gif-анимации
 * @param {String} frames перечисление кадров
 * @param {string} mime тип изображения (по умолчанию image/png)
 * @param {Function} callback
 */
function extractFrames(file, frames, mime, callback) {
  // начала нужно сконвертировать файл в base64
  fileToBase64(file, function(data){

    // опции для gif-frames
    var options = {
      // ссылка на файл. Т.к. файл загружается не по ссылке
      // а выбирается пользователем, мы привели файл к ссылке
      url: data,
      frames: frames, // кадры для извлечения
      outputType: 'canvas' // тип результата
    };

    // вызов функции библиотеки gif-frames
    gifFrames(options, function(error, data){
      var $canvas,
          $image,
          result = [];

      for (var i = 0; i < data.length; i++) {
        $canvas = data[0].getImage(); // извлекаем результат в виде html-элемента canvas
        $image = new Image(); // создаём пустое изображение
        $image.src = $canvas.toDataURL(mime); // извлекаем изобажение из canvas

        result.push({
          $canvas: $canvas,
          element: $image,
          width: $canvas.width,
          height: $canvas.height
        });
      }

      // возвращаем результат
      callback(result);
    });
  });
}

// при клике на кнопку "Извлечь"
$extract.addEventListener('click', function(){

  // выбираем всю неоходимую информацию введённую
  // в поля формы
  var file = $file.files[0],
      frames = $frames.value,
      type = $type.value;

  // проверка введённых данных
  if (file instanceof File === false || file.type !== 'image/gif') {
    alert('Необходимо выбрать GIF-файл');
    $file.click();
    return;
  }

  if (!frames) {
    alert('Укажите какие кадры нужно извлечь из анимации\nФормат: 1, 2-4, 5, 6)');
    $frames.focus();
    return;
  }

  // вызов функции извлекающей кадры
  extractFrames(file, frames, type, function(images){

    // очистка списка изображений
    $output.innerHTML = '';

    // перебираем извлечённые кадры
    for (var i = 0; i < images.length; i++) {
      var image = images[i],
          $item = document.createElement('li'),
          $element = image.element;

      // меняем размер картинки
      $element.width = 200;
      $element.height = 200 / (image.width / image.height);

      // выгружаем данные в DOM
      $item.appendChild($element);
      $output.appendChild($item);
    }
  });
});
.controls {
  padding: 10px;
  background: #fafafa;
  border: 1px solid gray;
}

.control {
  padding: 10px;
}

.control > label {
  min-width: 80px;
  display: block;
  float: left;
}

.output {
  list-style: none;
}

    File
    <input type="file" name="file" id="file">

    Frames
    <input type="text" name="frames" id="frames" value="1">

    Type
    <select name="type" id="type">
      <option value="image/png">PNG</option>
      <option value="image/jpeg">JPEG</option>
    </select>

    <input type="button" name="extract" id="extract" value="Извлечь">


text:
Q: Get rows from one datatable where Id not in another using Powershell I have two DataTables in Powershell with differing columns but one common Id column.
I want to get the rows from DataTable A where the Id of the row doesn't appear in DataTable B.
|DataTable A                |
|---------------------------|
|Id|SomeName|SomeDescription|
|--|--------|---------------|
|1 |Blah    |Whatevs        |
|2 |Foo     |Bar            |
|3 |Woo     |Yeah           |

|DataTable B                         |
|------------------------------------|
| Id | SomeOtherName | SomeOtherDesc |
|----|---------------|---------------|
| 1  | Blah blah     | Yadda yadda   |
| 2  | Foo foo       | Bah bah       |

The result I'd like:
|DataTable Result                |
|---------------------------|
|Id|SomeName|SomeDescription|
|--|--------|---------------|
|3 |Woo     |Yeah           |

How is this best done in Powershell?

A: Quickly whipped a csv table and not a data table, but if the ID columns are put in an array, this should work,:
$tableA = @'
Id,somename,somedescription
1,Blah,Whatevs
2,Foo,Bar
3,Woo,Yeah
'@

$tableB = @'
Id,somename,somedescription
1,Blah,Whatevs asd
2,Foo,Bar asd
'@

$importA = $tableA | Convertfrom-csv
$importB = $tableB | Convertfrom-csv

$importA | Where-Object { $importB.Id -notcontains $_.Id }

A: Since you work with DataTables and the result should also be a DataTable, this should do it:
# DataTable A
$dtA = New-Object System.Data.DataTable
$dtA.Columns.Add([System.Data.DataColumn]::new("Id",[int]))
$dtA.Columns.Add([System.Data.DataColumn]::new("SomeName"))
$dtA.Columns.Add([System.Data.DataColumn]::new("SomeDescription"))

$row = $dtA.NewRow()
$row["Id"] = 1
$row["SomeName"] = "Blah"
$row["SomeDescription"] = "Whatevs"
$dtA.rows.Add($row)

$row = $dtA.NewRow()
$row["Id"] = 2
$row["SomeName"] = "Foo"
$row["SomeDescription"] = "Bar"
$dtA.rows.Add($row)

$row = $dtA.NewRow()
$row["Id"] = 3
$row["SomeName"] = "Woo"
$row["SomeDescription"] = "Yeah"
$dtA.rows.Add($row)

# DataTable B
$dtB = New-Object System.Data.DataTable
$dtB.Columns.Add([System.Data.DataColumn]::new("Id",[int]))
$dtB.Columns.Add([System.Data.DataColumn]::new("SomeOtherName"))
$dtB.Columns.Add([System.Data.DataColumn]::new("SomeOtherDesc"))

$row = $dtB.NewRow()
$row["Id"] = 1
$row["SomeOtherName"] = "Blah blah"
$row["SomeOtherDesc"] = "Yadda yadda"
$dtB.rows.Add($row)

$row = $dtB.NewRow()
$row["Id"] = 2
$row["SomeOtherName"] = "Foo foo"
$row["SomeOtherDesc"] = "Ba ba"
$dtB.rows.Add($row)

# create a clone of datatable A (no data, just the structure)
$dtResult = $dtA.Clone()

# Get the Id values that are in DataTable A, but not in DataTable B
$diff = Compare-Object -ReferenceObject $dtA.Id -DifferenceObject $dtB.Id -PassThru | Where-Object { $_.SideIndicator -eq '<=' }
$dtA | Where-Object { $diff -contains $_.Id } | ForEach-Object {
    # here, $_ is of type System.Data.DataRow

    # you cannot add this DataRow directly because it belongs to another DataTable,
    # to overcome that use the 'ItemArray' property to get an array of the values inside
    $null = $dtResult.Rows.Add($_.ItemArray)
}

$dtResult

Result (type System.Data.DataTable):

Id SomeName SomeDescription
-- -------- ---------------
 3 Woo      Yeah


text:
Q: How can I force in Jquery so that the focus event of a background changed textbox has the correct value? I'm changing a textbox (child) based on a value entered by the user into an other textbox (parent).
This is done using following Jquery:
$(this).val(newData).trigger('change');

When changing directly the focus from the parent to the child textbox using the mouse or tabbing, the child textbox still has the old value in the focus event of the child textbox.
On the blur event, the child textbox has the correct new value.
When I set the focus first to an totally different control, and then go to the child textbox, the value in the focus event of the child textbox is correct.
what is going on, and how can I force an update of the child textbox value, so that it is always registered in the focus event ?

A: perhaps you mean this? I prefer to use the
master -slave

terminology in this case ;)
child = slave

like:
/**
  just add/change events like change blur keyup keydown you can play with
**/

$("input[name='master']").bind("blur", function() {
   $("input[name='slave']").val($(this).val());
});

test here:
http://jsfiddle.net/8SYKZ/


text:
Q: Azure SQL DB find all Tables in all Databases Perhaps this is not even possible but I am interested in seeing all Tables across all my Azure SQL DB Databases.
I can use sys.databases to get a list of Databases and sys.tables to get a list of Tables but cannot seem to figure out the correct combination to return Tables per Database.
Is this possible in Azure using straight T-SQL?  If not, is there a practicable alternative?

A: We can use straight T-SQL in Azure SQL DB.
According to your requirements, I have some demos for your reference:
Get all tables in a specify data base:
    /// <summary>
    /// get all Tables in a data base
    /// </summary>
    /// <param name="DataBaseName">For example: MyDataBase1</param>
    /// <returns></returns>
    public ActionResult QueryAllTables(string DataBaseName)
    {
        ContentResult content = new ContentResult();

        SqlConnection conn = new SqlConnection("Server=tcp:dotxxxxxxx.database.windows.net,1433;Initial Catalog="+ DataBaseName + ";Persist Security Info=False;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
        try
        {
            conn.Open();
            SqlCommand command = new SqlCommand();
            command.Connection = conn;
            command.CommandType = System.Data.CommandType.Text;
            command.CommandText = "select id,name from sysobjects where xtype='U'";
            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    string tableInfo  = "id:"+reader[0].ToString()+ " name:"+reader[1].ToString();
                    content.Content += tableInfo + "\r\n";
                }
            }
            else
            {
                content.Content = "No Table";
            }

        }
        catch (Exception ex)
        {
            content.Content = ex.Message;
        }
        return content;
    }

Screenshot of result:

Get all tables from each data base
    /// <summary>
    /// get all data bases' names
    /// </summary>
    /// <returns></returns>
    public List<string> QueryAllDbName()
    {
        ContentResult content = new ContentResult();
        List<string> list = new List<string>();
        using (SqlConnection conn = new SqlConnection("Server=tcp:xxxxxxx.windows.net,1433;Initial Catalog=DotNetAppSqlDb20180410043804_db;Persist Security Info=False;User ID=xxxxx;Password=xxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))
        {
            try
            {
                conn.Open();
                SqlCommand command = new SqlCommand();
                command.Connection = conn;
                command.CommandType = System.Data.CommandType.Text;
                command.CommandText = "SELECT Name FROM SysDatabases ORDER BY Name";
                SqlDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string DbName = reader[0].ToString();
                        list.Add(DbName);
                    }
                }
                else
                {
                    list = null;
                }

            }
            catch (Exception ex)
            {
                content.Content = ex.Message;
            }
        }

        return list;
    }

    public ActionResult QueryAllTablesFromEachDb()
    {
        ContentResult content = new ContentResult();
        List<string> DbNames = QueryAllDbName();
        foreach (string DbName in DbNames)
        {
            using (SqlConnection conn = new SqlConnection("Server=tcp:xxxxxxxxx.database.windows.net,1433;Initial Catalog="+ DbName + ";Persist Security Info=False;User ID=xxxxxx;Password=xxxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))
            {
                try
                {
                    conn.Open();
                    SqlCommand command = new SqlCommand();
                    command.Connection = conn;
                    command.CommandType = System.Data.CommandType.Text;

                    content.Content += "DataBase Name: " + DbName + "\r\n";
                    command.CommandText = "select id,name from sysobjects where xtype='U'";
                    SqlDataReader reader = command.ExecuteReader();
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            string tableInfo = "     Table id:" + reader[0].ToString() + " Table name:" + reader[1].ToString();
                            content.Content += tableInfo + "\r\n";
                        }
                    }
                    reader.Close();

                }
                catch (Exception ex)
                {
                    content.Content = ex.Message;
                }
            }
        }
        return content;
    }

Screenshot of result:


text:
Q: cocos2d iphone 5 4 inch display support I have been looking everywhere for this but with no luck.
How do I prepare my cocos2d based game for bigger 4 inch display of the iPhone 5?
My app is working but i want to enhance it for the bigger 4 inch display.
Cocos2d uses its own suffixes for retina display images. For retina display of the iPhone 4 and 4S it is image-hd.png. Is there a suffix for iPhone 5? How do I accomplish this?
Cheers.

A: Add it to AppDelegate:
[CCFileUtils setiPadRetinaDisplaySuffix:@"your suffix"];
[CCFileUtils setiPadSuffix:@"your suffix"];
[CCFileUtils setiPhoneFourInchDisplaySuffix:@"your suffix"];
[CCFileUtils setiPhoneRetinaDisplaySuffix:@"your suffix"];

A: Not sure why everyone is saying there isn't.
The suffix is -568h for iPhone5/iPod Touch 5th (so the 4 inch retina displays).
The total list:

*

*-hd (iPhone 4/4S, iPod Touch 4th)

*-568h (iPhone 5, iPod Touch 5th)

*-ipad (iPad 1st/2nd)

*-ipadhd (iPad 3rd/4th)

A: Add this to AppDelegate with your chosen suffix:
if((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) && ([[UIScreen mainScreen] bounds].size.height == 568)) {
    [sharedFileUtils setiPhoneRetinaDisplaySuffix: @"-your suffix"];
}

A: It took me awhile to figure this out, since I'm new to cocos2d. So I thought a recap might be helpful for those like me. In cocos2d 2.1, all you have to do is creating graphics for the target screen sizes and follow cocos suffix naming convention. Note that cocos's suffix convention is not the same as iOS's.
In my case, I have a background image that occupies the full screen. So, I made...

*

*background.png at 480x320 for iPhone

*background-hd.png at 960x640 for iPhone retina (3.5")

*background-iphone5hd.png for iPhone5 retina (4")

And use the following code to load the image into CCSprite. Cocos will figure out which image to use for you.
CCSprite *background = [CCSprite spriteWithFile:@"background.png"];
background.position = ccp(background.textureRect.size.width/2,
background.textureRect.size.height/2);
[self addChild:background];

For an element like a character that doesn't occupy the full screen, cocos2d will pickup character-hd.png automatically in iPhone5. There is no need to create character-iphone5hd.png version.
You can read more about this in version 2.1 release note at
https://github.com/cocos2d/cocos2d-iphone/wiki/cocos2d-v2.1-release-notes

A: This is how i did it for cocos2d v2.1-beta4.
In CCFileUtils.h i added:
- (void)setIphone5HDSuffix:(NSString *)suffix;

In CCFileUtils.m:
- (void)setIphone5HDSuffix:(NSString *)suffix
{
   [_suffixesDict setObject:suffix forKey:kCCFileUtilsiPhone5HD];
}

In AppDelegate.m:
[sharedFileUtils setIphone5HDSuffix:@"your_suffix"];

And that's enough!

A: There is no extra file suffix for iPhone 5, after all it's only 176 pixels (88 points) wider. It's treated like a regular Retina phone, hence cocos2d will load the -hd files.
The rest is just about positioning your images depending on the device. The simplest way is to just treat the 44 points on either side as a "dead zone" where no user input can occur and where there's no guarantee the user can see game objects.
Update:
cocos2d 2.1 added the -widehd suffix. It was said that 2.1 final release will have the suffix renamed to -iphone5hd.
In light of future screen sizes I sould personally set and use a -568hd suffix because other phones beside iPhone 5 may have the same resolution. Naming the suffix after a specific iPhone model is a tad short-sighted to say the least.

A: Did you follow the following post, adding the default image for it, named Default-568h@2x.png with a resolution of 1136x640?
How to develop or migrate apps for iPhone 5 screen resolution?
If it does not work, I found this post on cocos2d forum, containing a lot of infos:
iPhone 5 1136 x 640 screen resolution: http://www.cocos2d-iphone.org/forum/topic/39491

A: Now cocos2d support iPhone wide screen also.
 -wide.png for iphone 5
 -widehd.png for iPhone 5 HD

A: I was just playing around with suffixes in Cocos2D 2.1-rc1 and was able to get it to automatically load a iPhone5 file with the "-iphone5hd" suffix, not changing anything in AppDelegate in the sharedFileUtil section of code.  Hope that helps, also.


text:
Q: Trouble installing release Apk I am new to Android studio. I just finished making an app. I made a signed release Apk and I can install it on my phone and some other phones, but I can't install it on many other devices.
here is what I did in detail:

*

*from "build variant" menu, I chose "release". (as it is written here: https://stackoverflow.com/a/30586280)

*I created my APK using build > Generate signed bundle/apk and used my keystore.

*for signature version, I chose both options (V1 & V2)

*the APK was created successfully.

*I copied this APK to several devices: a Huawei Y7, a Huawei honor 6, a Motorola moto G5 plus, a samsung J7, and a Nokia 3. (I used huawei Y7 during developement for debugging. Moto G5 plus and Samsung J7 belong to my friends and I sent them the APK file using email.)

*the APK was successfully Installed on Nokia 3 and Huawei Y7 and my app worked fine (as I expected)

*I wasn't able to Install the APK on Huawei honor 6 and Samsung J7. I got an "install failed" message from android package Installer.

*on the Moto G5 plus, I successfully Installed my App but it stopped working before even the main activity showed up.

*I connected the Huawei honor 6 to my laptop and was able to install the APK via USB Debugging and the app worked fine, as I expected. but I still couldn't install the app on this device Using the signed APK that I created using android studio.

A: I solved this issue by adding this in my build.gradle (app) file:
    splits {
        abi {
            enable true
            universalApk true
        }
    }


text:
Q: Prevent gnome from automatically mounting partition when clicked in nautilus I have two partitions on a hard drive in my machine that are formatted as ntfs, but must under no circumstance be mounted by my Ubuntu installation (unless I do some preparation first). However nautilus happily displays the partitions, and a single click will mount them automatically.
This is very dangerous behaviour, how can I hide the partitions from nautilus and prevent accidentally mounting them by a single stray mouse click?
Thanks
Update: I have been experimenting with writing udev rules, however I have not been able to get it working. If anybody has the specific steps needed to modify udev as to not show specific partitions, I would really appreciate it.

A: You can write a udev rule that prohibits non-root users from mounting the partition.
You could also hide the partition icons on your desktop by running gconf-editor and unchecking volumes_visible in /apps/nautilus/desktop.


text:
Q: is there a way to render a form when a button is pressed ? PHP I am looking for some help in core PHP. I want to know how to display a form in a window when a button is pressed. It should be like the conditional rendering in react or svelte etc. I don't want to use any framework any laravel.

A: You can use a button and have that other page open via an url like this
<button type="button" onclick='"location.href="someurl.php?someparams"'>Some button</button>

Where the single quote enclosure on the onclick means the double quotes get sourced correctly. The "type" on button as button is so if this were enclosed in a form, the form will not confuse it with submit behavior.
Hopes this helps.


text:
Q: Extraer información importante de una oración utilizando spacy Estoy intentando extraer lo que quiere hacer la persona en ciertas oraciones. Por ejemplo, en "mi consulta que quiero saber como para pagar pagar mi linea el telefono me van a mandar factura a mi casa o al telefono como es eso" lo importante es que la persona quiere saber como pagar. En "si quiero saber cuanto voy a pagar el mes que viene si no dame de baja la linea" quiere saber cuanto va a pagar el mes que viene. En "quiero saber como debo pagar y cuanto debo pagar quiero conocer mis consumos mis mis vencimiento etcetera" quiere saber cuanto debe pagar.
Es decir, extraer la información asociada a lo que la persona quiere saber/hacer. Un ejemplo más, en "que quiero que que pagara el minimo del abono que me es mucho lo que estoy pagando y no puedo pagar a ver los otros dias y o hable xx horas estuve con alguien y y voy a saber cuantas pague y tengo que pagar un monto que no tenemos mucho" lo importante es pagar el minimo del abono.
Probé usando spacy, intentando encontrar las palabras que dependen de "quiero saber", "quiero", "saber", etc, pero no encuentro la forma de extraer lo adecuado.


text:
Q: Checking if develop branch has been merged into feature branch? I have a script bumping the version and making a commit with the bump and tagging it. The issue I am having is making sure develop gets fetched from remote then merged into feature branch to insure no conflicts during the PR merge.
How do I check that the feature and develop are in sync merged?

A: The git branch command will show you branches that are merged, or are not merged.  For instance, if you are on branch main and branch side was merged in at some point, but another branch ahead has not yet been merged:
$ git branch --merged
* main
  side
$ git branch --no-merged
  ahead
$

It's possible (but somewhat painful) to use this to check.  But if you just want to test one specific pair of branches (or indeed any specific pair of commits), the "is / is-not merged" quality is simply whether one is an ancestor of another, in terms of the commit graph.
The git merge-base command has a mode in which it performs this test, for two specific commits (which you may specify in any form listed in the gitrevisions documentation):
$ if git merge-base --is-ancestor side main; then
>     echo side is merged into main
> fi
side is merged into main
$

The test that git branch --merged uses (for each branch, comparing it to the current branch) is the same as the test git merge-base --is-ancestor uses, i.e., the SHA-1 that the first commit (here side^{commit}) is an ancestor of the current branch's tip commit.  (A commit is considered an ancestor of itself, so you always get your own current branch from git branch --merged.  Assuming of course that you are on a branch in the first place—if you're in "detached HEAD" state, the list of all named branches does not include your detached HEAD.)


text:
Q: read in numbered files in right order I have 1500 files in one directory and I need to get some information out of every one and write it into a new, single file. The file names consist of a word and a number (Temp1, Temp2, Temp3 and so on) and it is important that the files are read in the correct order according to the numbers.
I did this using
my @files = <Temp*.csv>;

for my $file (@files)
    {
       this part appends the required data to a seperate file and works fine
    }

my problem now is that the files are not opened in the correct order but after file 1 the file 100 gets opened.
Can anybody please give me a hint how I can make it read the files in the right order?
Thank you,
Ca

A: Sort the files naturally with Sort::Key::Natural natsort.
The following will automatically sort the files naturally, separating out alpha and numerical portions of the name for the appropriate sort logic.
use strict;
use warnings;

use Sort::Key::Natural qw(natsort);

for my $file ( natsort <Temp*.csv> ) {
    # this part appends the required data to a seperate file and works fine
}

The following fake data should demonstrate this module in action:
use strict;
use warnings;

use Sort::Key::Natural qw(natsort);

print natsort <DATA>;

__DATA__
Temp100.csv
Temp8.csv
Temp20.csv
Temp1.csv
Temp7.csv

Outputs:
Temp1.csv
Temp7.csv
Temp8.csv
Temp20.csv
Temp100.csv

A: You can use Schwartzian transform to read and sort files in one step,
my @files =
  map { $_->[0] }
  sort { $a->[1] <=> $b->[1] }
  map { [ $_, /(\d+)/ ] } <Temp*.csv>;

or using less efficient, and more straightforward sort,
my @files = sort { ($a =~ /(\d+)/)[0] <=> ($b =~ /(\d+)/)[0] } <Temp*.csv>;

A: If the numbers are really important, you might want to read them specifically after file name, with error reporting about missing files:
my @nums = 1 .. 1500;  # or whatever the highest is

for my $num (@nums) {
    my $file = "Temp$num.csv";
    unless (-e $file) {
        warn "Missing file: $file";
        next;
    }
    ...
    # proceed as normal
}

If you need a file count, you can simply use your old glob:
my @files = <Temp*.csv>;
my $count = @files;       # get the size of the array
my @nums = 1 .. $count;

On the other hand, if you control the process that prints the files, you might select a format that will automatically sort itself, such as:
temp00001.csv
temp00002.csv
temp00003.csv
temp00004.csv
...
temp00101.csv


text:
Q: NullPointerException while inserting data into SqliteDatabase Android Android 2.3.3
static String name = "Database";
static int version = 1;

static SQLiteDatabase sqlDB;
static Cursor c;

public Database(Context context) {
    super(context, name, null, version);
    // TODO Auto-generated constructor stub

    sqlDB = getWritableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase sqlDB) {
        // TODO Auto-generated method stub

    sqlDB.execSQL("create table if not exists Operations(Command Text, Pos1 Text, " +
                "Pos2 Text, Pos3 Text, Pos4 Text, Pos5 Text, Pos6 Text, Pos7 Text, Pos8 Text, Pos9 Text, Pos10 Text)");

        insertData();
    }

private void insertData() {
        // TODO Auto-generated method stub

        String addQuery ="ADD, add, and, had, ad, anddd, anndd, null, null, null, null";

                sqlDB.execSQL("insert into Operations values("+ addQuery +")");
                     //Exception at the above line
}

There are a total of 11 columns.
Can i insert NULL into the database?
If yes, is there any problem with the way i am trying to insert the data into the database?
As pointed out by rekire, it seems the problem is with the getWritableDatabase(). I am calling the constructor with , Database db = new Database(this); which worked in all other projects till now, as i have declared the local variables for name and version and provided null to the factory.

Answer ::: Sorry it's my mistake. I called a method in the database,
  by using Database.method(), instead of it's object(db). This made the
  SQLiteDatabase and Cursor objects to be static in the Database.java
  file. When i changed it to db.method(), and removed the static
  keyword, it works fine.

Thanks for your time.. And sorry for the trouble.

A: If I guess right than your function getWritableDatabase() returns null.

A: You'll want to call the open() method before you make the query
mDbHelper.open(); //whitout this call mdb will be NULL

A: private void insertData() {
    if(sqlDB == null) sqlDB.open();
    String addQuery ="ADD, add, and, had, ad, anddd, anndd, null, null, null, null";
    sqlDB.execSQL("insert into Operations values("+ addQuery +")");
}

A: in your
 public void onCreate(SQLiteDatabase sqlDB)

you should assign sqlDB = sqlDB;
then you can use sqlDB in insertData()


text:
Q: Client Side authentication with ReactJs I'm still learning full-stack Development and I'm following this tutorial to create the API but I can't wrap my head around authentication on the client-side. So I'm using ReactJs in the frontend and I can't figure out how to keep track of a logged-in user(to show his name and his profile picture on the navbar for example). I've read about storing the logged-in user in the localStorage and how it's not secure enough.
this is the code for creating a new user and logging him in. I'm using ExpressJs and JWT
const createSendToken = (user, statusCode, res) => {
const token = signToken(user.id);
res.cookie("jwt", token, {
expires: new Date(
  Date.now() + 90 * 24 * 60 * 60 * 1000
),
secure: true,
httpOnly: true,
});
user.password=undefined;
res.status(statusCode).json({
status: "success",
token,
data: {
  user,
},
});
};
exports.signup = async (req, res, next) => {
const newUser = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm,
});
createSendToken(newUser, 201, res);
};

A: You can store the token in state and ask your api for a refresh token everytime you get a jwt expired error


text:
Q: How to retrieve list of data collection from fire store using bloc I am trying to retrieve list of collection of data from fire store as the the below one:

and this is my below States Class:
abstract class AppStates {}

class AppInitialState extends AppStates {}

class AppGetCategoriesLoadingState extends AppStates {}

class AppGetCategoriesSuccessState extends AppStates {}

class AppGetCategoriesErrorState extends AppStates {
  final String error;

  AppGetCategoriesErrorState(this.error);
}

And this is the below cubit class I have:
class AppCubit extends Cubit<AppStates> {
  AppCubit() : super(AppInitialState());

  static AppCubit get(context) => BlocProvider.of(context);

  List<CategoryModel> categoryModel;

  final CollectionReference _categoryCollectionRef =
      FirebaseFirestore.instance.collection('PetsCategories');

  Future<List<QueryDocumentSnapshot>> getCategory() async {
    var value = await _categoryCollectionRef.get();

    return value.docs;
  }

  void getCategoriesData() {
    emit(AppGetCategoriesLoadingState());
    getCategory().then((value) {
      // print(value.data());
      for (int i = 0; i < value.length; i++) {
        categoryModel.add(CategoryModel.fromJson(value[i].data()));
      }
      emit(
        AppGetCategoriesSuccessState(),
      );
    }).catchError((error) {
      print(error.toString());
      emit(
        AppGetCategoriesErrorState(
          error.toString(),
        ),
      );
    });
  }
}

and this is the below Screen I have:
return BlocConsumer<AppCubit, AppStates>(
      listener: (context, state) {},
      builder: (context, state) {
        var cubit = AppCubit.get(context);
        return Column(
          children: [
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: const EdgeInsets.only(left: 20.0),
              child: CustomText(
                text: "Categories",
              ),
            ),
            SizedBox(
              height: 30,
            ),
            Container(
              height: 100,
              child: ListView.separated(
                shrinkWrap: true,
                physics: BouncingScrollPhysics(),
                itemCount: cubit.categoryModel.length,
                scrollDirection: Axis.horizontal,
                itemBuilder: (context, index) {
                  return Column(
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(50),
                          color: Colors.grey.shade100,
                        ),
                        height: 60,
                        width: 60,
                        child: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Image.network(cubit.categoryModel[index].image),
                        ),
                      ),
                      // SizedBox(
                      //   height: 20,
                      // ),
                      CustomText(
                        text: cubit.categoryModel[index].name,
                      ),
                    ],
                  );
                },
                separatorBuilder: (context, index) => SizedBox(
                  width: 20,
                ),
              ),
            ),
          ],
        );
      },
    );

and this is the error I have:
The following NoSuchMethodError was thrown building BlocBuilder<AppCubit, AppStates>(dirty, state: _BlocBuilderBaseState<AppCubit, AppStates>#fe322):
The getter 'length' was called on null.
Receiver: null
Tried calling: length

The relevant error-causing widget was:
  BlocConsumer<AppCubit, AppStates> file:///Users/mahmoudalharoon/Desktop/IPetApp/IPet%20FlutterProject/ipet/lib/modules/discover/discover_screen.dart:17:12
When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      DiscoverScreen.build.<anonymous closure> (package:ipet/modules/discover/discover_screen.dart:40:48)
#2      BlocBuilder.build (package:flutter_bloc/src/bloc_builder.dart:90:57)
#3      _BlocBuilderBaseState.build (package:flutter_bloc/src/bloc_builder.dart:151:21)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
...

A: You are emitting your loading state which will trigger the BlocConsumer builder. To avoid this error, you'll need to check the state of the cubit to make sure that it is AppGetCategoriesSuccessState. This way the cubit will have defined the categoryModel variable and will be able to be used.
I would recommend to avoid class variables within your Cubit. It would be better to emit the state with the values that you want to display.
class AppGetCategoriesSuccessState extends AppStates {
   const AppGetCategoriesSuccessState({required this.values});
   final List<CategoryModel> values;
}

then in your bloc consumer

// within the BlocConsumer builder
if (state is AppGetCategoriesSuccessState){
   final _values = state.values;
   // use your values here
}

A: This is the full right code I figured...
Here's the CategoryModel Class:
class CategoryModel {
  String image;
  String type;

  CategoryModel({
    this.image,
    this.type,
  });

  CategoryModel.fromJson(Map<String, dynamic> map) {
    // if (map == null) {
    //   return;
    // }
    image = map['image'];
    type = map['type'];
  }

  Map<String, dynamic> toMap() {
    return {
      'type': type,
      'image': image,
    };
  }
}

this is the method which is in the cubit class:
  void getCategoriesData() {
    FirebaseFirestore.instance.collection('PetsCategories').get().then((value) {
      value.docs.forEach((element) {
        categories.add(CategoryModel.fromJson(element.data()));
      });
      emit(AppGetCategoriesSuccessState());
    }).catchError((error) {
      emit(AppGetCategoriesErrorState(error.toString()));
    });
  }

this is the below Screen:
class DiscoverScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocConsumer<AppCubit, AppStates>(
      listener: (context, state) {},
      builder: (context, state) {
        return Column(
          children: [
            SizedBox(
              height: 30,
            ),
            Padding(
              padding: const EdgeInsets.only(left: 20.0),
              child: CustomText(
                text: "Categories",
              ),
            ),
            SizedBox(
              height: 30,
            ),
            buildCategoryItem(context),
          ],
        );
      },
    );
  }

  Widget buildCategoryItem(context) {
    return Container(
      height: 100,
      child: ListView.separated(
        shrinkWrap: true,
        physics: BouncingScrollPhysics(),
        itemCount: AppCubit.get(context).categories.length,
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          return Column(
            children: [
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(50),
                  color: Colors.grey.shade100,
                ),
                height: 60,
                width: 60,
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Image.network(
                      AppCubit.get(context).categories[index].image),
                ),
              ),
              // SizedBox(
              //   height: 20,
              // ),
              CustomText(
                text: AppCubit.get(context).categories[index].type,
              ),
            ],
          );
        },
        separatorBuilder: (context, index) => SizedBox(
          width: 20,
        ),
      ),
    );
  }
}


text:
Q: TFS: Having Trouble Getting a Phonegap solution from TFS I am having trouble distributing my Phonegap solution from TFS.
The thing is the project works fine when I created the solution (builds an runs successfully) and was able to upload it to TFS successfully, but when other developers gets the solution it always returns an error when building.
This is the error my co-developers are receiving

I am using:

*

*Phonegap 2.4.0

*Windows Phone 7.8 SDK

*Visual Studio 2010

A: As per this answer, find CordovaSourceDictionary.xml in the project folder and check if it is read-only. If so, make it writable.


text:
Q: Alternative solutions to an array search in PostgreSQL I am not sure if my database design is good for this tricky case and I also ask for help how the query for this could look like.
I plan a query with the following table:
       search_array      | value | id
  -----------------------+-------+----
   {XYa,YZb,WQb}         | b     |  1
   {XYa,YZb,WQb,RSc,QZa} | a     |  2
   {XYc,YZa}             | c     |  3
   {XYb}                 | a     |  4
   {RSa}                 | c     |  5

There are 5 main elements in the search_array: XY, YZ, WQ, RS, QZ and 3 Values: a, b, c that are concardinated to each element.
Each row has also one value: a, b or c.
My aim is to find all rows that fit to a specific row in this sense: At first it should be checked if they have any same main elements in their search_arrays (yellow marked in the example).
As example:
Row id 4 an row id 5 wouldnt match because XY != RS.
Row id 1, 2 and 3 would match two times because they have all XY and YZ.
Row id 1 and 2 would even match three times because they have also WQ in common.
And second: if there is a Main Element match it should be 'crosschecked' if the lowercase letters after the Main Elements fit to the value of the other row.
As example: The only match for Row id 1 in the table would be Row id 4 because they both search for XY and the low letters after the elements match each value of the two rows.
Another match would be ROW id 2 and 5 with RS and search c to value c and search a to value a (green and orange marked).

My idea was to cut the search_array elements in the query in two parts with the RIGHT and LEFT command for strings. But I dont know how to combine the subqueries for this search.
Or would be a complete other solution faster? Like splitting the search array into another table with the columns 'foregin key' to the maintable, 'main element' and 'searched_value'. I am not sure if this is the best solution because the program would all the time switch to the main table to find two rows out of 3 million rows to compare their searched_values to the values?
Thank you very much for your answers and your time!

A: You'll have to represent the data in a normalized fashion. I'll do it in a WITH clause, but it would be better to store the data in this fashion to begin with.
WITH unravel AS (
   SELECT t.id, t.value,
          substr(u.val, 1, 2) AS arr_main,
          substr(u.val, 3, 1) AS arr_val
   FROM mytable AS t
      CROSS JOIN LATERAL unnest(t.search_array) AS u(val)
)
SELECT a.id AS first_id,
       a.value AS first_value,
       b.id AS second_id,
       b.value AS second_value,
       a.arr_main AS main_element
FROM unravel AS a
   JOIN unravel AS b
      ON a.arr_main = b.arr_main
         AND a.arr_val = b.value
         AND b.arr_val = a.value;


text:
Q: jQuery mouseenter and mouseleave fadeTo prevent delayed repeat So, I've got a div which fades up on mouse enter and down on mouseleave which works fine.
$('.myDiv').mouseenter(function(){
$(this).fadeTo('slow', 1);
});

$('.myDiv').mouseleave(function(){
$(this).fadeTo('slow', 0.4);
});

See jsfiddle .
However, if you quickly move the mouse over and back and again several times, the div will "flash" as the animation keeps running. Is there a way to stop this from occurring?
I've tried callbacks but haven't got the desired effect.
Any suggestions?

A: Try:
$('.myDiv').mouseenter(function(){
    $(this).stop();
    $(this).fadeTo('slow', 1);

});
$('.myDiv').mouseleave(function(){
    $(this).stop();
    $(this).fadeTo('slow', 0.4);
});

https://jsfiddle.net/1Lrcubwp/

A: A better way is to use CSS.
Javascript shouldn't be used for this kind of animation as it will make your website slow.
See my example below.

.fade {
        background-color: red;
    width: 200px;
    height: 200px;
   opacity: 0.4;
    filter: alpha(opacity=40); /* For IE8 and earlier */
   transition: opacity .25s ease-in-out;
   -moz-transition: opacity .25s ease-in-out;
   -webkit-transition: opacity .25s ease-in-out;
    cursor: pointer;
   }

   .fade:hover {
      opacity: 1;
      }


text:
Q: save all links in html page to pdf i really need help regarding importing a webpage to pdf at client side without using chrome pdf save api. This HTML page is being generated through a desktop application and My page contain frames and one frame shows html file according to link clicked, So is there any possible ways to import all links html along with images.
jsPDF is working fine but with the text and images i need to align manually, like for each and every image it would be hectic, so is there any way to import html to pdf with all links.


text:
Q: How to Access and Control a Document Scanner[ADF Front and Back] like Kodak or Hp from Python and Django I already tried Pyinsane2 to access the scanner. It communicate with Kodak scanner but it Scan only first page as clear and remaining pages are fully blur.
and also pyinsane2 is no more maintainable. and also i don't know how to use Libinsane which is successor of  Pyinsane2.
I need a help to control and scan from Python Django.
def scan_process(request):
    pyinsane2.init()
    try:
        devices = pyinsane2.get_devices()
        assert (len(devices) > 0)
        device = devices[0]
        print("I'm going to use the following scanner: %s" % (str(device)))
        try:
            pyinsane2.set_scanner_opt(device, "source", "ADF Front")
            # pyinsane2.set_scanner_opt(device, 'duplex', ['both'])
        except PyinsaneException:
            print("No document feeder found")
        pyinsane2.set_scanner_opt(device, 'mode', ['Color'])

        pyinsane2.maximize_scan_area(device)
        source = 'Auto'
        if (device.options['source'].constraint_type
                == pyinsane.SaneConstraintType.STRING_LIST):
            if 'Auto' in device.options['source'].constraint:
                source = 'Auto'
            elif 'FlatBed' in device.options['source'].constraint:
                source = 'FlatBed'
        else:
            print("Warning: Unknown constraint type on the source: %d"% device.options['source'].constraint_type)
        res = 200
        colour = 'Color'
        # set_scanner_opt(device, 'resolution', res)
        # set_scanner_opt(device, 'source', source)
        # set_scanner_opt(device, 'mode', colour)
        set_scanner_opt(device,'quality','maximum')
        # set_scanner_opt(device,'duplex','both')
        #
        pyinsane2.maximize_scan_area(device)
        scan_session = device.scan(multiple=True)

        try:
            while True:
                try:
                    scan_session.scan.read()
                except EOFError:
                    print("Got a page ! (current number of pages read: %d)" % (len(scan_session.images)))
        except StopIteration:
            print("Document feeder is now empty. Got %d pages" % len(scan_session.images))
        for idx in range(0, len(scan_session.images)):
            image = scan_session.images[idx]

            file_name = 'Scan_'
            file_extension = '.pdf' #.bmp
            file_name_new = file_name + str(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S"))
            lsfile_name = str((BASE_DIR + '/Bigflow_Demojs/media/' + file_name_new + file_extension))

            lsfile_name_db  = str(('/media/' + file_name_new + file_extension))

            path = Path(lsfile_name)
            path.parent.mkdir(parents=True, exist_ok=True)

            image.save(lsfile_name)   #### Save the Scanned Data

            # from io import BytesIO   ##### Detect The Barcode Data
            # buffered = BytesIO()
            # image.save(buffered, format="JPEG")
            # img_str = base64.b64encode(buffered.getvalue())
            # test = img_str
            #
            # obj_code = base64code.bar_qrcode()
            # obj_code.base64_data = img_str
            # ldict_data = obj_code.read_base64()
            #
            # barcode_data = ldict_data
            # img_path_db = lsfile_name_db
            #
            # out_data = {}
            # out_data = {"MESSAGE":"FOUND","DATA":ldict_data,"IMAGE_PATH":lsfile_name_db}

            # image.save("GRT_%d.bmp" % idx)
            # return JsonResponse(out_data,safe=False)

    except Exception as e:
        str(e)
    # finally:
        # pyinsane2.exit()

It need to scan all pages both front and back.


text:
Q: Unable access HEY_CURRENT_USER Environment variable in Rest service launched through Windows service Process restService = Process.Start("F:\\RestService\\RestService.exe");
Code is simple.
I have a created a windows service(C#) under local system account.
I have to launch a Rest service(C++) through it.
That rest service uses Environment variable FMS_HOME for FCC from HKEY_CURRENT_USER section.
When I run rest service standalone, it works fine.
But when I run rest service through windows service, FMS_HOME is not found.
How to solve this?

A: HKEY_CURRENT_USER as it's name implies is a key that stores data for the current user. I assume that you are using an integrated account to run your service, something like "Network Service", so you will not see the key because the account is not the same one that created the entry.
To solve it you have two options: store the keys in HKEY_LOCAL_MACHINE or launch your service with the same account that created the entries in the registry (I would not recommend it as it may create security problems).


text:
Q: Share file between Android Wear and mobile I'm triyng to share a file between a wear and a mobile.
I would like to know what is the best practice with an example.

*

*Using SharedPreferences ?

*Using a common library as dependancy which contain the file ?

*The file is in the mobile project and the wear access it ?

Thanks.

A: You have to use the (The Wearable Data Layer API) http://developer.android.com/training/wearables/data-layer/index.html.

The API consists of a set of data objects that the system can send and synchronize over the wire and listeners that notify your apps of important events with the data layer

A: Our answer is (2) - we typically create a common library (aka module in Android Studio) to share between our mobile and wear apps.
Please take a look at our SynchronizedNotifications sample under samples/android-20/wearable/. You will see a module called Common which contains the class Constants. This in turn contains all the URIs that we use to key off DataItems.