Q: np.insert() -1 as the position of an element I am playing with the NumPy library and there is a behaviour that I do not understand:
I defined a simple vector Y:
Y = np.array([6,7,8],dtype = np.int16)

Then, I tried to add an additional element at the end of the array using the np.insert()  method. I specified the position to be at -1:
Z = np.insert(Y,(-1),(19))

My element was inserted not on the last, but on the penultimate position:
Output
Could somebody explain my why this element was not inserted at the end of my array?

A: Negative indexes are calculated using len(l) + i (with l being the object and i being the negative index).
For example, with a list x = [1, 2, 3, 4] the index -2 is calculated as 4-2 = 2, so x[-2] returns 3
In this example, the index -1 is calculated as index 2
Therefore, 19 is inserted at index 2, the penultimate position. To fix this, use Z = np.insert(Y, len(Y), 19).
PS - this is the same with list.insert, not just with numpy arrays
Edit (suggested by Homer512): np.append may be easier than np.insert if you want to add to the end of an array: Z = np.append(Y, 19)


Q: why the computed method work on only one record? i did this method which compute the late hours of an employee and convert it at days in dedication filed on payslip, it working well but when there is more than one payslip and i need to get the sumition of dedication field of all payslips for an employee it give me just one record and return other records = 0.00 ,
here the methode
@api.multi
@api.depends('date_to','date_to','employee_id')
def compute_amount(self):
    for rec in self:
        rec.attend = self.env['hr.attendance'].search(
            [('check_in', '>=', rec.date_from), ('check_out', '<=', rec.date_to),
             ('employee_id', '=', rec.employee_id.id), ])
        late=[float(s.late) for s in rec.attend]
        tot_late= float(sum(late))
    rec.dedication = tot_late / 8
    pass

dedication = fields.Float(string="Dedication",  required=False,compute=compute_amount )

if i try to print all record i get a list like this [0.0, 0.0, 1.7551388888888888] if there is 3 payslips the list return only one record with the real value and other record = 0
any help will be apriciated

A: It's probably because the rec.dedication = tot_late / 8 is outside the for rec in self loop. Which means the value is only set on the last record it computes.
Also, the pass value seems unnecessary here.


Q: uisng multer with typescript: Property 'file' does not exist on type 'Request'.ts(2339) I am using https://www.npmjs.com/package/multer library and my node.js app is written in typescript.
I get the following typescript error in my code.

Property 'file' does not exist on type 'Request'.ts(2339)

    public document = async (req: Request, res: Response): Promise<any> => {
        const documentFile = req.file;
    }

How can i resolve this. The req is the express Request object but multers middleware appends a .file into this request object. However it is not aware of this because the types request interface does not originally contain a file properly

A: Like @daliusd mentioned in his answer, the accepted answer here should be:
npm i @types/multer --save-dev
req.files is now typed and recognized by the Typescript compiler.

A: Probably we can just extend Request
interface MulterRequest extends Request {
    file: any;
}

 public document = async (req: Request, res: Response): Promise<any> => {
   const documentFile  = (req as MulterRequest).file;
 }

or may be like this code
interface MulterRequest extends Request {
    file: any;
}

 public document = async (req: MulterRequest , res: Response): Promise<any> => {
   const documentFile  = req.file;
 }

A: Or install @types/multer with
npm i @types/multer --save-dev

and check out this https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18569

A: if using typescript with express-fileupload you can install @types/express-fileupload as dev dependencie and it will be solved


Q: Apache Beam count HBase row block and not return Start to try out the Apache Beam and try to use it to read and count HBase table. When try to read the table without the Count.globally, it can read the row, but when try to count number of rows, the process hung and never exit.
Here is the very simple code:
Pipeline p = Pipeline.create(options);

p.apply("read",    HBaseIO.read().withConfiguration(configuration).withTableId(HBASE_TABLE))
  .apply(ParDo.of(new DoFn<Result, String>() {
   @ProcessElement
   public void processElement(ProcessContext c) {
        Result result = c.element();
        String rowkey = Bytes.toString(result.getRow());
        System.out.println("row key: " + rowkey);
        c.output(rowkey);
   }
}))
.apply(Count.<String>globally())
.apply("FormatResults", MapElements.via(new SimpleFunction<Long, String>() {
      public String apply(Long element) {
          System.out.println("result: " + element.toString());
          return element.toString();
      }
 }));

when use Count.globally, the process never finish. When comment it out, the process print all the rows.
Anyy ideas?

A: Which version of beam are you using?
Thanks for bringing this issue. I tried to reproduce your case and indeed there seems to be an issue with colliding versions of guava that breaks transforms with HBaseIO. I sent a pull request to fix the shading of this, I will keep you updated once it is merged so you can test if it works.
Thanks again.


Q: Getting error Uninitialized ASN.1 value when trying to use pympler.tracker.SummaryTracker() I have a memory leak in my python2.7 code and I'm trying to debug it using pympler.
Traceback (most recent call last):
  File "eta/dynamic_eta_worker.py", line 29, in <module>
    tr = tracker.SummaryTracker()
  File "/usr/local/lib/python2.7/site-packages/pympler/tracker.py", line 45, in __init__
    self.s0 = summary.summarize(muppy.get_objects())
  File "/usr/local/lib/python2.7/site-packages/pympler/summary.py", line 131, in summarize
    total_size[otype] = _getsizeof(o)
  File "/usr/local/lib/python2.7/site-packages/pyasn1/type/base.py", line 145, in plug
    raise error.PyAsn1Error('Uninitialized ASN.1 value ("%s" attribute looked up)' % name)
pyasn1.error.PyAsn1Error: Uninitialized ASN.1 value ("__sizeof__" attribute looked up)

Tried to search here and in google and came out with nothing.
The thing is that when I call pympler.tracker.SummaryTracker() from the python console it works like a charm.
Thanks.

A: pip install -U pyasn1

please try to upgrade pyasn1 version


Q: Localizing XIB files - why there is a need I am beginner in iOS.
I learned how to localize XIB files.
This way two versions of my XIB file are created, say one for
English version and one for Spanish.
Here is sample of the spanish localized XIB:

I was curious why there is need for localizing XIB files?
I know how to localize any string using string tables
and NSLocalizedString() method. Is localizing XIB files
good because it is not possible/easy to use localized strings as titles
for the controls in the interface builder?

A: If you move to storyboards and autolayout you don't need to localize your UI, you just need to provide the localised strings files.

A:
Is localizing XIB files good because it is not possible/easy to use
  localized strings as titles for the controls in the interface builder?

The backside is, when you need to show a message to the user sometimes needed the label localized text without colon. The xib provides name with colon and without. Sometimes hard to keep in evidence what / where is in localized xib.
You can make an utility software to make easier the localisation of strings and editing those inline with many languages. That why I prefer strings localized over xib.


Q: How to start and stop jboss from apache ant build.xml file I have make
jar
war
EAR
using ant and Hudson and store all files at some temp folder
now I want to copy all war and ear files to jboss jboss/default/deploy folder using Apache ANT
How can I do this??
Following is my master build file
which call all other build.xml files and make jar war ear files
but after making this all files this don't copy all any of the files to jboss/default/deploy folder
<copy todir="${jbossdeploy.dir}" overwrite="yes">
        <fileset dir="${class.dir}/ear" includes="MessageBoardEAR.ear"/>

    </copy>

<project name="master" >

    <property name="class.dir" location="../Source/buildwork" />
    <property name="ecpsproperties.dir" location="D:\ecpsproperties\jars\platform" />
    <property name="jbossdeploy.dir" location="D:\jboss-6.1.0.Final\server\default\deploy" />

    <target name="clean">
        <delete dir="${class.dir}" />

    </target>

    <target name="makedir">
        <mkdir dir="${class.dir}" />
        <mkdir dir="${class.dir}/jar" />
        <mkdir dir="${class.dir}/ear" />
        <mkdir dir="${class.dir}/war" />
    </target>

<filelist id="projects" dir=".">
        <file name="../Source/ValueObjects/build.xml"/>
        <file name="../Source/ECPSValueObjects/build.xml"/>
        <file name="../Source/ECPSUtils/build.xml"/>
        <file name="../Source/CommonExceptions/build.xml"/>
         <file name="../Source/ECPSExceptions/build.xml"/>
         <file name="../Source/ECPSCommon/build.xml"/>
         <file name="../Source/BaseDAO/build.xml"/>
         <file name="../Source/PageManagerValueObjects/build.xml"/>
         <file name="../Source/PageManagerDAO/build.xml"/>
         <file name="../Source/ECPSDAO/build.xml"/>
         <file name="../Source/PageManagerEJBClient/build.xml"/>
         <file name="../Source/PartyEJBClient/build.xml"/>
          <file name="../Source/ReportsEJBClient/build.xml"/>
         <file name="../Source/StagingEJBClient/build.xml"/>
          <file name="../Source/MessageBoardEJBClient/build.xml"/>
         <file name="../Source/PageManagerFacade/build.xml"/>
          <file name="../Source/PartyFacade/build.xml"/>
         <file name="../Source/ReportsFacade/build.xml"/>
          <file name="../Source/StagingFacade/build.xml"/>
         <file name="../Source/MessageBoardFacade/build.xml"/>

          <file name="../Source/MessageBoardEJB/build.xml"/>
         <file name="../Source/MessageBoardEAR/build.xml"/>
         <file name="../Source/PageManagerEJB/build.xml"/>
          <file name="../Source/PageManagerEAR/build.xml"/>

           <file name="../Source/PartyEJB/build.xml"/>
         <file name="../Source/PartyEAR/build.xml"/>

         <file name="../Source/ReportsEJB/build.xml"/>
          <file name="../Source/ReportsEAR/build.xml"/>

          <file name="../Source/StagingEJB/build.xml"/>
         <file name="../Source/StagingEAR/build.xml"/>

          <file name="../Source/Admin/build.xml"/>
         <file name="../Source/eCPSClient/build.xml"/>
          <file name="../Source/MessageBoardServices/build.xml"/>
           <file name="../Source/OAuth/build.xml"/>
            <file name="../Source/PageManagerRest/build.xml"/>
             <file name="../Source/PartyServices/build.xml"/>
             <file name="../Source/ReportsServices/build.xml"/>
          <file name="../Source/StagingServices/build.xml"/>

 </filelist>

    <copy todir="${jbossdeploy.dir}" overwrite="yes">
        <fileset dir="${class.dir}/ear" includes="MessageBoardEAR.ear"/>

    </copy>

 <target name="main" depends="clean, makedir">
    <subant>

      <filelist refid="projects" />

    </subant>

 </target>
</project>

A: use copy task e.g.
<copy file="myfile.txt" todir="../some/other/dir"/>

A: this should work as I have added copy task under main :
<project name="master" >

<property name="class.dir" location="../Source/buildwork" />
<property name="ecpsproperties.dir" location="D:\ecpsproperties\jars\platform" />
<property name="jbossdeploy.dir" location="D:\jboss-6.1.0.Final\server\default\deploy" />

<target name="clean">
<delete dir="${class.dir}" />

</target>

<target name="makedir">
<mkdir dir="${class.dir}" />
<mkdir dir="${class.dir}/jar" />
<mkdir dir="${class.dir}/ear" />
<mkdir dir="${class.dir}/war" />
</target>

<filelist id="projects" dir=".">
<file name="../Source/ValueObjects/build.xml"/>
<file name="../Source/ECPSValueObjects/build.xml"/>
<file name="../Source/ECPSUtils/build.xml"/>
<file name="../Source/CommonExceptions/build.xml"/>
<file name="../Source/ECPSExceptions/build.xml"/>
<file name="../Source/ECPSCommon/build.xml"/>
<file name="../Source/BaseDAO/build.xml"/>
<file name="../Source/PageManagerValueObjects/build.xml"/>
<file name="../Source/PageManagerDAO/build.xml"/>
<file name="../Source/ECPSDAO/build.xml"/>
<file name="../Source/PageManagerEJBClient/build.xml"/>
<file name="../Source/PartyEJBClient/build.xml"/>
<file name="../Source/ReportsEJBClient/build.xml"/>
<file name="../Source/StagingEJBClient/build.xml"/>
<file name="../Source/MessageBoardEJBClient/build.xml"/>
<file name="../Source/PageManagerFacade/build.xml"/>
<file name="../Source/PartyFacade/build.xml"/>
<file name="../Source/ReportsFacade/build.xml"/>
<file name="../Source/StagingFacade/build.xml"/>
<file name="../Source/MessageBoardFacade/build.xml"/>

<file name="../Source/MessageBoardEJB/build.xml"/>
<file name="../Source/MessageBoardEAR/build.xml"/>
<file name="../Source/PageManagerEJB/build.xml"/>
<file name="../Source/PageManagerEAR/build.xml"/>

<file name="../Source/PartyEJB/build.xml"/>
<file name="../Source/PartyEAR/build.xml"/>

<file name="../Source/ReportsEJB/build.xml"/>
<file name="../Source/ReportsEAR/build.xml"/>

<file name="../Source/StagingEJB/build.xml"/>
<file name="../Source/StagingEAR/build.xml"/>

<file name="../Source/Admin/build.xml"/>
<file name="../Source/eCPSClient/build.xml"/>
<file name="../Source/MessageBoardServices/build.xml"/>
<file name="../Source/OAuth/build.xml"/>
<file name="../Source/PageManagerRest/build.xml"/>
<file name="../Source/PartyServices/build.xml"/>
<file name="../Source/ReportsServices/build.xml"/>
<file name="../Source/StagingServices/build.xml"/>

</filelist>

<target name="main" depends="clean, makedir">
<subant>

<filelist refid="projects" />

</subant>

<copy todir="${jbossdeploy.dir}" overwrite="yes">
<fileset dir="${class.dir}/ear" includes="MessageBoardEAR.ear"/>

</copy>
</target>
</project>


Q: Storyboard Scene Editor vanished I'm still new to Xcode and developing iOS apps...when I was editing my storyboard, I somehow removed the menu that displays  the list of scenes (which defaults to the right side of the file navigator).
How do you bring this menu/view back up?

A: If I understand what you want you must just click on the button at the bottom in yellow highlight:


Q: Advantage of Class component over react hooks Every where I see are the advantages of hooks over class component , but still class components in react do exist so can anyone tell me the advantages of class components over hooks?


Q: Image options to customize the visibility of tabs Expected behaviour: With respect to my use case, when the user clicks on image button, I must allow the user to only upload the image and hence I have to hide the URL tab.
Actual behaviour:   Currently there is no such option to hide the URL and to display only upload tab.


Q: Can you tell Google's gmail servers to ignore a missing messageID? We receive 12 emails daily from a vendor that supply data for management required reports.
We originally set up a Gmail account to receive these messages which are processed by a CRON job. We discovered early on that the messages were never recorded as received by the email client, so we had them sent to another account and then auto-forwarded.
This worked fine for a lot of months, then suddenly, a few months ago, messages that were auto-forwarded were randomly being rejected (the number of messages rejected has increased, but occasionally one or two still get through.) Interestingly, when we forward the messages manually, they go through just fine.
Since we owned the account that was doing the auto-forwarding, we received the bounce backs. The bounce message from mailer-daemon@googlemail.com was comprised of a graphic of a stop light with the red light lit, and the text:
Your message to destination_email@gmail.com has been blocked. See technical details below for more information.

Below that is the technical details:
The response was:<br />550 5.7.1 [209.85.220.41] Messages missing a valid messageId header are not accepted. s198-20020a632ccf000000b0042a2fdfda1csor3403081pgs.60 - gsmtp

When we look at the header of the original message received from the data vendor we see this is the message ID:
<6302575f.810a0220.ceb0b.5763SMTPIN_ADDED_MISSING@mx.google.com>

When we forward the message manually (which are always received), a complete message ID is included in the forwarded message.
We asked the vendor to either update their SMTP server to include a message ID, or programatically
add a generated message ID (e.g., using a library such as Python has) so that their messages were compliant with the RFC, and were told that for security reasons they cannot do that. So we are on our own.
Please note that we cannot just put a rule into the receiving Gmail account telling it to accept these messages, they are never received by the client, they are being blocked at Google.
Is there a way to tell the Gmail servers for this account to ignore the message ID? Or is there another way we can work around this?


Q: AVAudioPlayer Not Working upon SpriteKit Scene Loading I was struggling hardcore with a simple task: Play an audio file in the background when a SpriteKit scene loads.
I copied an audio file named "Test Song.wav" into my project and it was also found in my assets when I look under "Build Phases" > "Copy Bundle Resources" (which was what this post suggested to check for)
My code compiled just fine, and my ring/silent switch was correctly turned to ring, but the audio didn't play when the scene loaded.
I'm using

*

*Xcode Version 8.0 beta

*iPhone 6S Plus running iOS 10 Beta 1

Here was my broken code:
import AVFoundation

class GameScene: SKScene {

    override func didMove(to view: SKView) {

        if let path = Bundle.main().pathForResource("Test Song", ofType: "wav") {

        let filePath = NSURL(fileURLWithPath:path)

        let songPlayer = try! AVAudioPlayer.init(contentsOf: filePath as URL)

        songPlayer.numberOfLoops = 0

        songPlayer.prepareToPlay()

        songPlayer.play()

        }
    }
}

Note: I learned that in Swift 3.0, AVAudioPlayer's init() method no longer accepted the NSError parameter, so this code DOES NOT compile:
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)

A: Thanks to this website I learned that my problem was the scope of my AVAudioPlayer object.
Here is the working code:
class GameScene: SKScene {

    var songPlayer:AVAudioPlayer?

    override func didMove(to view: SKView) {

        if let path = Bundle.main().pathForResource("Test Song", ofType: "wav") {

            let filePath = NSURL(fileURLWithPath:path)

            songPlayer = try! AVAudioPlayer.init(contentsOf: filePath as URL)

            songPlayer?.numberOfLoops = 0 //This line is not required if you want continuous looping music

            songPlayer?.prepareToPlay()

            songPlayer?.play()

        }
    }
}


Q: How to set attributes while dynamically creating enum using EnumBuilder I have to create Enum dynamically from XML.
XML format is as below:
<?xml version="1.0" encoding="utf-8"?>
<Category xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Game>
    <Name>Tekken</Name>
    10
  </Game>
  <Game>
    <Name>NFS</Name>
    20
  </Game>
  <Game>
    <Name>FinalFa</Name>
    40
  </Game>
</Category>

I want to create Enum which looks like this:
[DataContract]
[Flags]
public enum Category
{
    [EnumMember]
    Tekken = 10,
    [EnumMember]
    NFS = 20,
    [EnumMember]
    FinalFa = 40,
}

So far I have been able to create this:
 public enum Category
    {
        Tekken = 10,
        NFS = 20,
        FinalFa = 40,
    }

C# code used to generate the Enum:
   private static void Create()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;
            AssemblyName asmName = new AssemblyName("EnumAssembly");
            AssemblyBuilder asmBuilder = currentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
            ModuleBuilder mb = asmBuilder.DefineDynamicModule(asmName.Name, asmName.Name + ".dll");
            EnumBuilder eb = mb.DefineEnum("MyNamespace.Category", TypeAttributes.Public, typeof(int));

            FieldBuilder fb1 = eb.DefineLiteral("Tekken", 10);
            FieldBuilder fb2 = eb.DefineLiteral("NFS", 20);
            FieldBuilder fb3 = eb.DefineLiteral("FinalFa", 40);

            Type eType = eb.CreateType();
            asmBuilder.Save(asmName.Name + ".dll");

            foreach (object obj in Enum.GetValues(eType))
            {
                Console.WriteLine("{0}.{1} = {2}", eType, obj, ((int)obj));
            }
        }

How can I add the attributes [DataContract], [Flags] and [EnumMember] to my enum?

A: As you see, the DefineLiteral method returns a FieldBuilder (fb1, fb2, fb3). You can use SetCustomAttribute on the FieldBuilder to set an attribute. The linked MSDN article has an example on how to use it. The gist of it though, would be to use a CustomAttributeBuilder to build your attribute, then give it to SetCustomAttribute.

A: Not exactly sure but something like this:
Type myType = typeof(DataContract);
ConstructorInfo myInfo = myType.GetConstructor();

eb.SetCustomAttribute(myInfo);


Q: How to access data inside Json nested objects from an API I am using cryptocomare API to get crypto coins data within a Nextjs App. What i doing is that when a user clicks on a perticular symbol, i redirect it to the coin details page where i try to extract the clicked symbol with getServerSideProps as follows and then dynamically put in the API call and send it to the API server.
`
export const getServerSideProps = async (context) => {
  const res = await fetch(
    `https://min-api.cryptocompare.com/data/pricemultifull?tsyms=USD&fsyms=${context.params.symbol}`
  );
  const icon = await res.json();
  return {
    props: {
      icon,
    },
  };
};

`
This call returns a json object of nested objects and it goes to 2-3 levels deep. On Top it looks like following:
API call response
Inside my code, I want to access the data Object -> RAW -> (whatever the user clicked on). But, Since the Symbol or coin queried by the user is dynamic (means i can't predict what is clicked) I never know what to query. SO i tried this to access the data object.RAW[0]
In principal it should give me the whatever object is inside the object.RAW But it returns undefined
Can please someone guide me , how can i get the data inside object.RAW without knowing what is inside?
Thanks!
I have tried object.RAW[0] to access the data...,....

A: You can use Object.values(object.RAW) to get an array of the values inside RAW (assuming RAW is not undefined)
Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values


Q: goodness of fit of umap I'm given a 20122-dim matrix, each column is a 20-element vector. Now I apply umap to the matrix and get a 2122 matrix and a umap plot. How to measure the goodness of fit of this umap model? Is there any standard way to do that?

A: UMAP has multiple purposes like clustering, supervised learning and outlier detection.
What exactly do you want to do with UMAP?
In case of clustering, you can take a look at sklearn cluster evaluation and compare the scores with other algorithms like t-SNE.
To look for the structure, you can reduce your data to 2-3 dimensions and use a scatter plot to eye check the results.
When you have labeled data, you can try to classify them with (nonlinear) classifiers like a random forest and compare the result score (e.g. accuracy) with other dimension reduction techniques like PCA.
Maybe you look for the trustworthiness from sklearn. You can compare the scores of PCA with the score of UMAP or any other dimension reduction algorithm. source


Q: How to flip a pdf page upside down using python? I'm trying to flip pdf pages upside down using python. I have tried multiple libraries like PyPdf2, PyMuPDF and pdfminer. There is documentation on how to rotate a page, but that is not what I'm looking for. The closest solution I found was on one of PyMuPDF documentation pages, but its an example and doesn't offer the code as to how it was achieved. You can find the example page here: https://pymupdf.readthedocs.io/en/latest/matrix.html#flipping . Again the task is to flip the pdf pages not to rotate them.
Thank you, in advance for your answers.

A: The flipping is achieved by multiplying with a matrix that is initialized with those parameters:
# Flip the page left-right (a = -1).
destpage.showPDFpage(r * fitz.Matrix(a=-1), src, sourcepage.number)

OR:
# Flip the page up-down (d = -1).
destpage.showPDFpage(r * fitz.Matrix(d=-1), src, sourcepage.number)


Q: How to constrain method to return type where : Attribute I have an attribute
[System.AttributeUsage(System.AttributeTargets.Class]
public class ModuleValues : System.Attribute
{
    public Guid? Id { get; set; }

    public ModuleValues(string id)
    {
        Id = Guid.Parse(id);
    }
}

How can I create a generic method that returns the attribute once found?
public static T GetAttribute<T>(Type type) where T : Attribute
{
    object[] attrs = typeof(T).GetCustomAttributes(true);
    foreach (Attribute attr in attrs)
    {
        if (attr.GetType() == typeof (T))
        {
            //Console.WriteLine(attr.ToString());
            return attr as T;
        }
    }

    return default(T);
}

With the constraint in place, my method always returns null.
When I remove the constraint, I can find the attribute with a Console.WriteLine but cannot return it because the line return attr as T; gives compile error The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint
Example usage from my console:
Assembly x = Assembly.GetAssembly(typeof(MyBase));

Type[] types = x.GetTypes();
foreach (Type type in types)
{
    if (type.IsSubclassOf(typeof (MyBase)))
    {
        ModuleValues s = CustomAttributeHelper.GetAttribute<ModuleValues>(type);
        Console.WriteLine("S" + s);
    }
}

A: This should be:
object[] attrs = type.GetCustomAttributes(true);

Changing typeof(T) to input type. The GetCustomAttributes method gets attributes ON the called type.

A: This line is the problem:
object[] attrs = typeof(T).GetCustomAttributes(true);

You're calling GetCustomAttributes on Type - not on the type that you're actually interested in. You want:
object[] attrs = type.GetCustomAttributes(true);

Or rather more simply, replace the rest of the method with:
return (T) type.GetCustomAttributes(typeof(T), true).FirstOrDefault();

Note that that will also pick up attributes which are subclasses of T, but I'd expect that to be more useful anyway, in the rare cases where you're actually using inheritance on attributes.


Q: Ttransforming XML using XSLT with count I am trying to transform the following XML using XSLT
Input XML
<lst name="facet_pivot">
    <arr name="party-name,entry-number,release-number">
        <lst>
            <str name="field">party-name</str>
            <str name="value">XYZ CONSULTANTS</str>
            <int name="count">348</int>
            <arr name="pivot">
                <lst>
                    <str name="field">entry-number</str>
                    <null name="value"/>
                    <int name="count">1</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">1</int>
                        </lst>
                    </arr>
                </lst>
                <lst>
                    <str name="field">entry-number</str>
                    <null name="value"/>
                    <int name="count">1</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">1</int>
                        </lst>
                    </arr>
                </lst>
                <lst>
                    <str name="field">entry-number</str>
                    <null name="value"/>
                    <int name="count">1</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">1</int>
                        </lst>
                    </arr>
                </lst>
                <lst>
                    <str name="field">entry-number</str>
                    <str name="value">8300012706</str>
                    <int name="count">1</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">1</int>
                        </lst>
                    </arr>
                </lst>
                <lst>
                    <str name="field">entry-number</str>
                    <str name="value">8300012821</str>
                    <int name="count">1</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">1</int>
                        </lst>
                    </arr>
                </lst>
                <lst>
                    <str name="field">entry-number</str>
                    <str name="value">8300018075</str>
                    <int name="count">1</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">1</int>
                        </lst>
                    </arr>
                </lst>
                <lst>
                    <str name="field">entry-number</str>
                    <str name="value">8300018083</str>
                    <int name="count">1</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">1</int>
                        </lst>
                    </arr>
                </lst>
                <lst>
                    <str name="field">entry-number</str>
                    <str name="value">8300018133</str>
                    <int name="count">1</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">1</int>
                        </lst>
                    </arr>
                </lst>
                <lst>
                    <str name="field">entry-number</str>
                    <str name="value">8300018141</str>
                    <int name="count">1</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">1</int>
                        </lst>
                    </arr>
                </lst>
                <lst>
                    <str name="field">entry-number</str>
                    <null name="value"/>
                    <int name="count">270</int>
                    <arr name="pivot">
                        <lst>
                            <str name="field">release-number</str>
                            <null name="value"/>
                            <int name="count">270</int>
                        </lst>
                    </arr>
                </lst>
            </arr>
        </lst>
    </arr>
</lst>

into something like
required Output XML
<reply>
    <party-name>XYZ CONSULTANTS</party-name>
    <count>348</count>
    <no-entry-release-count>4</no-entry-release-count>
</reply>

And Iam having issues transforming  .
I have tried using following xsl template
    <xsl:for-each select="lst">
                <ns:party-name><xsl:value-of select="str[@name='value']"/></ns:party-name>
                <ns:shipments-count><xsl:value-of select="int[@name='count']" /></ns:shipments-count>

                <xsl:for-each select="arr[@name='pivot']">
                    <xsl:if test="lst/null[@name='value'] = '' and lst/arr[@name='pivot']/lst/null[@name='value']/text() = ''">
                        <ns:no-entry-or-line-release-count>
                            <xsl:value-of select ="count(lst/null[@name='value'] = '' and lst/arr[@name='pivot']/lst/null[@name='value']/text() = '')"> </xsl:value-of>
                        </ns:no-entry-or-line-release-count>
                    </xsl:if>
                </xsl:for-each>
    </xsl:for-each>
</xsl:template>

but count always returns 1.Seems i am doing some thing wrong.
I am not able to figure it out why it is always returning one.
Any help is appreciated.

A: You can use this template to get required counts.
<xsl:template match="lst/arr/lst">
        <ns:reply>
            <ns:party-name>
                <xsl:value-of select="str[@name='value']"/>
            </ns:party-name>
            <ns:shipments-count>
                <xsl:value-of select="int[@name='count']" />
            </ns:shipments-count>
            <ns:no-entry-or-line-release-count>
                <xsl:value-of select ="count(arr[@name='pivot']/lst[count(str[@name='value'])=0]/arr[@name='pivot']/lst/int[@name='count'])"> </xsl:value-of>
            </ns:no-entry-or-line-release-count>
        </ns:reply>
    </xsl:template>


Q: SwiftUI UIHostingController navigation title animation broken When I use a UIHostingController to push a new SwiftUI.View to the navigation stack of an existing UIKit UIViewController the animation of the title in the navigation bar is broken. I tested in Xcode 12.0 on a pure new project.
Watch carefully the title "UIHostingController". You can see how the animation looks different from normal push animation, it just "appears" out of nothing and looks broken. The second animation happens already from SwiftUI.NavigationLink which looks fine.
Here is a link to the sample project if you want to try it out:
https://www.dropbox.com/s/mjkuzhpsb6yvlir/HostingControllerTest.zip?dl=0
See this GIF image: (open in another browser tab if you don't the see GIF animation)

This is the code behind:
class ViewController: UIViewController {
    private let button = UIButton(frame: .zero)

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "UIHostingController Title Test"
        self.view.backgroundColor = UIColor.white

        self.view.addSubview(self.button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle("Push UIHostingController", for: .normal)
        button.addTarget(self, action: #selector(Self.pushVC), for: .touchUpInside)
        button.setTitleColor(.blue, for: .normal)

        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
            button.widthAnchor.constraint(equalTo: self.view.widthAnchor),
            button.heightAnchor.constraint(equalToConstant: 50)
        ])
    }

    @objc private func pushVC() {
        let vc = UIHostingController(rootView: Content())
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

struct Content: View {
    var body: some View {
        NavigationLink(destination: Content2()) {
            Text("Push NavigationLink")
        }
        .navigationTitle("UIHostingController")
    }
}

struct Content2: View {
    var body: some View {
        Text("Coming from NavigationLink")
            .navigationTitle("Native SwiftUI View")
    }
}

A: Found the solution for this issue. UIHostingController is in fact just a normal UIViewController (with some add-ons for SwiftUI). Which means everything which is available for a UIViewController is as well available for UIHostingController. So the solution for this is to set everything related to the navigation bar on UIHostingController and not in the wrapped SwiftUI View.
let vc = UIHostingController(rootView: Content())
vc.title = "My custom title"

Also all navigations buttons work much better if directly set on UIHostingController. A good alternative is also to directly derive from UIHostingController and implement custom needed behavior there.

A: To force UIHostingController to set up its navigation item we can pre-render it in a separate window:
let window = UIWindow(frame: .zero)
window.rootViewController = UINavigationController(rootViewController: hostingController)
window.isHidden = false
window.layoutIfNeeded()

The window could even be cached for pre-rendering other views.


Q: Insufficient access rights on cross-reference id in Salesforce when attempting to insert object from Mule I signed up for a Salesforce developer account and then created an Account object in Salesforce.  I then ran a mule workflow to insert an Order object into Salesforce and it returns this error against the Account Id:
[SaveResult  errors='{[1][Error  fields='{[0]}'
 message='insufficient access rights on cross-reference id: 0010Y00000A7kCp'
 statusCode='INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY'
]
,}'
 id='null'
 success='false'
]

The same data is inserted successfully from https://workbench.developerforce.com so looks like something to do the call coming from Mule.  Is there a setting for external applications that needs to be activated?
There is only one user which is me and is the same one I used to create the Salesforce account and it has System Administrator privileges.
When I change the login credentials to my other Salesforce developer account it works (this other account was setup in 2015).
Is there a setting that needs to be changed or permissions added and if so how and where would I do this?
Datamapper looks like this for the salesforce developer account that fails:
output.Pricebook2Id = "01s0Y0000026KHiQAM";
output.AccountId = "0010Y00000A7kCpQAJ";
output.Status = "Draft";
output.Type = "Order";
output.BillingCity = "New York";
output.EffectiveDate = str2date("2016-10-16","yyyy-MM-dd");

Thanks for any help


Q: Invalid action configuration: Exception while trying to read the task definition artifact file I have a Codepipeline that deploys an ECR image to an ECS cluster using an ECS Blue / Green Deployment action. The pipeline contains two sources: one for the ECR image using an AWS ECR action and another one for fetching the configuration from Github using a ThirdParty Github action. The ECR action outputs an image artifact while the Github action outputs a config artifact. Both of these artifacts are provided as an input to the ECS Blue / Green Deployment action.
The pipeline fails at the ECS Blue / Green Deployment action with the following error (visible from AWS console):

Invalid action configuration
Exception while trying to read the task definition artifact file from: config

Here is the structure of the pipeline (some details are edited for anonymity):
$ aws codepipeline get-pipeline --name my-codepipeline
{
  "pipeline": {
    "name": "my-codepipeline",
    "roleArn": "arn:aws:iam::123456789000:role/my-codepipeline-role",
    "artifactStore": {
      "type": "S3",
      "location": "my-codepipeline-s3"
    },
    "stages": [
      {
        "name": "Source",
        "actions": [
          {
            "name": "ImageSource",
            "actionTypeId": {
              "category": "Source",
              "owner": "AWS",
              "provider": "ECR",
              "version": "1"
            },
            "runOrder": 1,
            "configuration": {
              "ImageTag": "latest",
              "RepositoryName": "my-ecr"
            },
            "outputArtifacts": [
              {
                "name": "image"
              }
            ],
            "inputArtifacts": []
          },
          {
            "name": "ConfigSource",
            "actionTypeId": {
              "category": "Source",
              "owner": "ThirdParty",
              "provider": "GitHub",
              "version": "1"
            },
            "runOrder": 1,
            "configuration": {
              "Branch": "master",
              "OAuthToken": "****",
              "Owner": "me",
              "PollForSourceChanges": "false",
              "Repo": "application-config"
            },
            "outputArtifacts": [
              {
                "name": "config"
              }
            ],
            "inputArtifacts": []
          }
        ]
      },
      {
        "name": "Deploy",
        "actions": [
          {
            "name": "DeployBackend",
            "actionTypeId": {
              "category": "Deploy",
              "owner": "AWS",
              "provider": "CodeDeployToECS",
              "version": "1"
            },
            "runOrder": 1,
            "configuration": {
              "AppSpecTemplateArtifact": "config",
              "AppSpecTemplatePath": "production/appspec.yaml",
              "ApplicationName": "my-codedeploy",
              "DeploymentGroupName": "my-codedeploy-group",
              "Image1ArtifactName": "image",
              "Image1ContainerName": "IMAGE_NAME",
              "TaskDefinitionTemplateArtifact": "config",
              "TaskDefinitionTemplatePath": "production/taskdef.json"
            },
            "outputArtifacts": [],
            "inputArtifacts": [
              {
                "name": "image"
              },
              {
                "name": "config"
              }
            ]
          }
        ]
      }
    ],
    "version": 1
  },
  "metadata": {
    "pipelineArn": "arn:aws:codepipeline:ap-northeast-1:123456789000:my-codepipeline",
    "created": 1564107543.285,
    "updated": 1564107543.285
  }
}

I have checked the compressed artifact in the S3 and it definitely contains the configuration files in the Github repository at the location specified by AppSpecTemplatePath and TaskDefinitionTemplatePath.
Here is the content of appspec.yaml:
$ cat production/appspec.yaml
version: 0.0
Resources:
  - TargetService:
      Type: AWS::ECS::Service
      Properties:
        TaskDefinition: <TASK_DEFINITION>
        LoadBalancerInfo:
          ContainerName: "my-container"
          ContainerPort: 80

A: After extensively trying out things, I stumbled upon a thread in a foreign language which I cannot find it. The thread said something about the artifact being passed to the action cannot be larger than 3 MB.
I solved my problem by reducing the size of the artifact (config). The configuration repository is shared among many projects and by moving those items to another project, I decreased the compressed artifact size from 14 MB to 3 kB. Miraculously, everything worked fine. AWS if you are reading this, please add more documentation about the artifact size limits to ECS CodeDeploy as I don't see any mention about this and I have no way of debugging this problem with such a general error message.

A: As far as I understand there are three major things we have to check as even if there is a syntax issue on file we might get the exception

*

*Files exists on correct path and you have already verified this.

*Content of the both taskdef.json file and appspec.yaml is proper without any syntax error and we can always refer to this document [1] for it.

*Also make sure that image has correct place holder "<IMAGE1_NAME>".

*Also if these options don't work then you may try to create on test public github repo just put taskdef.json and appspec.yaml file in it and test the same thing.

[1] Tutorial: Create a Pipeline with an Amazon ECR Source and ECS-to-CodeDeploy Deployment  - https://docs.aws.amazon.com/codepipeline/latest/userguide/tutorials-ecs-ecr-codedeploy.html

A: Thought I know a little about artifact config and could not found any help.
I created another codecommit repo where i stored appspec.yml and taskdef.json file only and followed this aws userguide. And this worked
Previously I was committing those file with main project repo. But every time it failed in deploy state with this message.[Exception while trying to read the task definition artifact file from ...]
I felt safe this way in production codebuild and codedeploy are separated in pipeline.
I created artifact pipeline and build pipeline. Two pipeline. To blue/green ECS service.


Q: Foundation 5 off-canvas full height of device I'm using Foundation's off-canvas navigation, attempting to make a navigation that takes up the full height of the device.
By default, the height of the menu options are determined by the height of the content being shown. This means if your content is less than the height of the menu items, your menu items will be invisible.
I would like both the menu, and the height of the content section to be fixed at the height of the device. With only scrolling in the content section if needed.
Setting the height, and min-height of content area to 100% doesn't seem to have any effect - only using a fixed height e.g. 500px will change the height - but then this isn't scalable.
How is this achieved?
If I give '.inner-wrap' a fixed height, the whole thing will adjust. How can I make sure .inner-wrap takes the full height of a device?

Label

link

link

link

blah blah

test

A: Try if this works, first enclose the
 in another div

         [..]

And then set the following css,
body,html{
    height:100%;
    width:100%;
}

.off-canvas-wrap,.inner-wrap{
    height:100%;
}

If you want to block scrolling, say for a chat client, set .page height to 100%. And that would be
body,html{
    height:100%;
    width:100%;
}
.off-canvas-wrap,.inner-wrap{
    height:100%;
}
.page{
    height:100%;
}

A: This is the best way I've found and its pretty simple and non-hackish
NOTE: this only works on some css3 browsers. Compatible Browsers

Sass Version:
.off-canvas-wrap {
  .inner-wrap{
    min-height: 100vh;
  }
}

CSS Version:
.off-canvas-wrap, .off-canvas-wrap > .inner-wrap {
  min-height: 100vh;
}

Edit:

Foundation 6 sites version
.off-canvas-wrapper-inner, .off-canvas{
  min-height: 100vh;
}

A: I had the same problems and this is what i've done:
i put .off-convas-wrapper , .inner-wrapper and aside out of my main content and just use .right(left)-off-canvas-toggle inside my body and my problem has solved.
with this way i dont need contents anymore.
BTW i put .exit-off-canvas at the end of my main content befor closing inner-wrapper tag

A: I had to hack the JS a bit, I found that depending on when the content is taller than the browser/device height or does not push to 100% height there were issues. Here’s my suggested fix: https://github.com/zurb/foundation/issues/3800


Q: Using FOR XML to group against 2 sql tables I have a sql query below, that I would like to format as XML using the FOR XML syntax.
SELECT
  gr.id,
  gr.created,
  ts.ordernumber
FROM trGrouped gr
INNER JOIN transactions ts
  ON ts.grouped_id = gr.id
WHERE ts.ordernumber IN ('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018')

This is an example of the XML format I would like the query to look like.
<trans_groups>
  <grouped id="56" created="4/14/2017">
    <ordernumber>1022108100000001</ordernumber>
    <ordernumber>1022108100000002</ordernumber>
    <ordernumber>1022108100000003</ordernumber>
  </grouped>
  <grouped id="57" created="4/14/2017">
    <ordernumber>1022109100000001</ordernumber>
    <ordernumber>1022109100000002</ordernumber>
  </grouped>
</trans_groups>

So far I have not been able to get this quite right. I have tried the following but this is not grouping the orders.
select gr.id as [@id], gr.created as [@created],
    (
    SELECT ts.ordernumber as ordernumber
    )
FROM trGrouped gr inner join transactions ts on ts.grouped_id = gr.id
    where ts.ordernumber in('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018')
FOR XML PATH('grouped'), ROOT('trans_groups')

A: Here is one approach
Example
Declare @YourTable table (id int,created date, ordernumber varchar(25))
Insert Into @YourTable values
 (56,'04/14/2017','1022108100000001')
,(56,'04/14/2017','1022108100000002')
,(56,'04/14/2017','1022108100000003')
,(57,'04/14/2017','1022109100000001')
,(57,'04/14/2017','1022109100000002')

Select [@id]      = id
      ,[@created] = convert(VARCHAR(10), created, 101)
      ,(
        Select ordernumber
         From  @YourTable A1
         Where A1.id = A.id
         For XML Path(''), type
       )
 From  (Select Distinct ID,Created From @YourTable ) A
 For XML Path('grouped'), Root('trans_groups')

Returns
<trans_groups>
  <grouped id="56" created="04/14/2017">
    <ordernumber>1022108100000001</ordernumber>
    <ordernumber>1022108100000002</ordernumber>
    <ordernumber>1022108100000003</ordernumber>
  </grouped>
  <grouped id="57" created="04/14/2017">
    <ordernumber>1022109100000001</ordernumber>
    <ordernumber>1022109100000002</ordernumber>
  </grouped>
</trans_groups>

A: This is working for me.
select gr.id as [@id], gr.created as [@created],
    (
    SELECT ordernumber as ordernumber from transactions where grouped_id = grouped_id
    and ordernumber in ('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018')
    FOR XML path(''), type
    )
FROM (SELECT distinct gr.id, created FROM trGrouped gr inner join transactions ts on ts.grouped_id = gr.id
    where ts.ordernumber in('4003970100000383', '4003970100000376', '4003970100000369', '1022108100000018')) gr
FOR XML PATH('grouped'), ROOT('trans_groups')


Q: Can't convert object of type java.lang.String to type - Firebase Error its firebase Error I cant get it please Help me to solve and tell me the reason why its happens.
sorry For english and try to solve it
    E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.kunalgharate.weedon, PID: 16793
              com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.kunalgharate.weedon.Friends
                  at com.google.android.gms.internal.zg.zzb(Unknown Source)
                  at com.google.android.gms.internal.zg.zza(Unknown Source)
                  at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                  at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:22)
                  at com.firebase.ui.database.ObservableSnapshotArray.getObject(ObservableSnapshotArray.java:160)
                  at com.firebase.ui.database.CachingObservableSnapshotArray.getObject(CachingObservableSnapshotArray.java:40)
                  at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:180)
                  at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:217)
                  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6482)
                  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6515)
                  at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458)
                  at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5563)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5559)
                  at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2229)
                  at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556)
                  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516)
                  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608)
                  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)
                  at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3410)
                  at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1710)
                  at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:346)
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:871)
                  at android.view.Choreographer.doCallbacks(Choreographer.java:683)
                  at android.view.Choreographer.doFrame(Choreographer.java:616)
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:857)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6123)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

Application terminated.
Activity Main
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;
    RecyclerView mSubsList;
    DatabaseReference mFriendsDatabase;
    DatabaseReference mUsersDatabase;
    private String mCurrent_user_id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.main_page_toolbar);
        setSupportActionBar(toolbar);
         getSupportActionBar().setTitle("WeedON");
        mAuth = FirebaseAuth.getInstance();
        mCurrent_user_id = mAuth.getCurrentUser().getUid();
        mSubsList =findViewById(R.id.subscribes_list);
        mSubsList.setHasFixedSize(true);
        mSubsList.setLayoutManager(new LinearLayoutManager(this));

        mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child("subscribers").child(mCurrent_user_id);
        mFriendsDatabase.keepSynced(true);
        mUsersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
        mUsersDatabase.keepSynced(true);

    }

    private void signOut() {
        mAuth.signOut();
    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Friends,MainViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Friends,MainViewHolder>(

                Friends.class,
                R.layout.single_service_layout,
                MainViewHolder.class,
                mFriendsDatabase
                )
        {
            @Override
            protected void populateViewHolder(MainViewHolder viewHolder, Friends model, int position) {

            }
        };

       mSubsList.setAdapter(firebaseRecyclerAdapter);
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        getMenuInflater().inflate(R.menu.main_menu, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        if(item.getItemId() == R.id.main_logout_btn){

          //  mUserRef.child("online").setValue(ServerValue.TIMESTAMP);

            signOut();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
         //   sendToStart();

        }

        if(item.getItemId() == R.id.main_settings_btn){

            Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
            startActivity(settingsIntent);

        }

        if(item.getItemId() == R.id.main_all_btn){

            Intent settingsIntent = new Intent(MainActivity.this, AllServicesActivity.class);
            startActivity(settingsIntent);

        }

        return true;
    }

    public static class MainViewHolder extends RecyclerView.ViewHolder{

        View mView;

        public MainViewHolder(View itemView) {
            super(itemView);

            mView =itemView;
        }

    }

}

Database Screenshot
enter image description here
its Not showing layout Error or code Error what should i do ?

A: By looking at your database I can see that your mFriendsDatabase DatabseReference points to some 'String' Values and you are telling your firebaseRecyclerAdapter that those are of type 'Friends,that is why the exception is thrown.Most probably your are doing a mistake while saving the value to database,instead of saving a Friends object you are saving some String value.But if that's not the case you can change your firebaseRecyclerAdapter to this...
FirebaseRecyclerAdapter<String,MainViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<String,MainViewHolder>(

            String.class,
            R.layout.single_service_layout,
            MainViewHolder.class,
            mFriendsDatabase
            )
    {
        @Override
        protected void populateViewHolder(MainViewHolder viewHolder, String mString, int position) {
          Log.d("TAG",mString);
        }
    };

   mSubsList.setAdapter(firebaseRecyclerAdapter);

A: To display those messages, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("subscribers").child(mCurrent_user_id);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String message = ds.getValue(String.class);
            Log.d("TAG", message);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);


Q: how to get in extjs getHours() values in 12 hours format currently getting hour values in 24 hours format Ext.application({
    name: 'Fiddle',
    launch: function () {
        var t1 = Ext.create('Ext.form.field.Time', {
            xtype: 'timefield',
            name: 'in',
            fieldLabel: 'Time In',
            minValue: '6:00 AM',
            maxValue: '8:00 PM',
            increment: 60,
            renderTo: Ext.getBody()
        });
        var time = Ext.Date.add(new Date(), Ext.Date.HOUR, + 14).getHours(); //getting hour values in 24 format want in 12 hours format
        t1.setMaxValue(time); //unable to setMaxValue
    }
});

A:
You can use Ext.Date class for getting 12 hours format.

Here is defied some formats:-

*

*g 12-hour format of an hour without leading zeros 1 to 12

*i Minutes, with leading zeros 00 to 59

*a Lowercase Ante meridiem and Post meridiem am or pm

*A Uppercase Ante meridiem and Post meridiem AM or PM

I have created an Sencha fiddle demo it is showing how is working. Hope this will help you to solve your problem.
Ext.create('Ext.form.Panel', {
    title: 'Time Card',
    width: 300,
    bodyPadding: 10,
    renderTo: Ext.getBody(),
    defaults: {
        xtype: 'timefield',
        minValue: '6:00 AM',
        maxValue: '8:00 PM',
        increment: 30,
        anchor: '100%',
        listeners: {
            change: function (timefield, newValue) {
                Ext.Msg.alert('Succes', 'Good you have selected ' + Ext.Date.format(newValue, 'g:i A') + '');
            }
        }
    },
    items: [{
        name: 'in',
        fieldLabel: 'Time In'
    }, {
        name: 'out',
        fieldLabel: 'Time Out'
    }, {
        xtype: 'button',
        text: 'Get current GMT+14 Time',
        handler: function () {
            var date = new Date(),
                dateGmtPlus14 = new Date(date.valueOf() + date.getTimezoneOffset() * 60000); //Multiply this by 60,000 (milliseconds in a minute) to get the milliseconds and subtract from the date to create a new date

            Ext.Msg.alert('Succes', 'Current time with GMT+14 is
 12 hours format : ' + Ext.Date.format(dateGmtPlus14, 'g:i:s A') +
                '
24 hours format:  ' + Ext.Date.format(dateGmtPlus14, 'G:i:s') + '');
        }
    }]
});

You can use Date.getTimezoneOffset() or MDN. This returns the time difference between your date and GMT in minutes.
Multiply this by 60,000 (milliseconds in a minute) to get the milliseconds and subtract from the date to create a new date.
new Date(date.valueOf() + date.getTimezoneOffset() * 60000)


Q: IF-THEN-ELSE statements in postgresql I'm looking to write a postgresql query to do the following :
if(field1 > 0,  field2 / field1 , 0)

I've tried this query, but it's not working
if (field1 > 0)
then return field2 / field1 as field3
else return 0 as field3

thank youu

A: In general, an alternative to case when ... is coalesce(nullif(x,bad_value),y) (that cannot be used in OP's case). For example,
select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from (     (select 'abc' as x, '' as y)
 union all (select 'def' as x, 'ghi' as y)
 union all (select '' as x, 'jkl' as y)
 union all (select null as x, 'mno' as y)
 union all (select 'pqr' as x, null as y)
) q

gives:
 coalesce | coalesce |  x  |  y
----------+----------+-----+-----
 abc      | abc      | abc |
 ghi      | def      | def | ghi
 jkl      | jkl      |     | jkl
 mno      | mno      |     | mno
 pqr      | pqr      | pqr |
(5 rows)

A: case when field1>0 then field2/field1 else 0 end as field3

A: As stated in PostgreSQL docs here:

The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.

Code snippet specifically answering your question:
SELECT field1, field2,
  CASE
    WHEN field1>0 THEN field2/field1
    ELSE 0
  END
  AS field3
FROM test


Q: Conditional redirect URL java It's realted to Conditional redirect the current URLs to new URLs, so that I can write "ONE script" and copy it into all the current old HTMLs for the same script. It would help those users whom had bookmarked the old URL and redirect to the new URL.
I have an old webpeges like

*

*www.oldsite.com/a1.html

*www.oldsite.com/a1/5698.html

*www.oldsite.com/x1.html

*www.oldsite.com/YY1.html
and want to get current URL of an user and using location.path and redirect to newsite.com base on the path (suffix)
ie

*

*www.oldsite.com/a1.html  to www.newsite.com/b1.html

*www.oldsite.com/a1/5698.html to www.newsite.com/b1/5698.html

*www.oldsite.com/x1.html to www.newsite.com/99.html

*www.oldsite.com/YY1.html  to www.newsite.com/ZZ1.html
I have tried many times but fail!
Since I am a new comer to HTML, can anyone can help me?
My site held more than a hundred old html!
Here is my draft
 <html>
 <head>
 <javascript>
 if window.location.path='/al.html'

  {
 window.location="http://www.newsite.com/b1.html"}

  else if window.location.path='/al/5698.html'

  {
 window.location="http://www.newsite.com/b1/5698.html"}
   .........

 </script>
  </head>

A: Given
import java.net.URI;

URI oldUri;

you can do that translation by creating a new uri from the old.
URI newUri = new URI(
    oldUri.getScheme(),
    "www.newsite.com",
    translatePath(oldUri.getPath()),
    oldUri.getQuery(),
    oldUri.getFragment());

You haven't provided enough examples for me to know what translatePath should do, but given a string like "/a1.html" it returns "/b1.html".


Q: Multiply Vector Elements by Vector to Return a Square Matrix I am fairly new to APL and am struggling to multiply each element of a vector v by the vector in such a fashion that it returns an n x n square matrix where n is the length of the vector.
For example,
    v ← 1 0 0 1.

I have attempted to create a function such as:
    ⍳⍴v{⍵×⍵[⍺]}v

    1 4 9 16

I am failing to iterate the ioda through the vector, which is one part I need guidance on. My overall goal is to return a matrix:
v_1 x v --> 1 0 0 1
v_2 x v --> 0 0 0 0
v_3 x v --> 0 0 0 0
v_4 x v --> 1 0 0 1
I will keep trying to figure this out. Any help is appreciated, thanks!

A: "Outer product" comes to rescue:
       (⍳10)∘.×⍳10
 1  2  3  4  5  6  7  8  9  10
 2  4  6  8 10 12 14 16 18  20
 3  6  9 12 15 18 21 24 27  30
 4  8 12 16 20 24 28 32 36  40
 5 10 15 20 25 30 35 40 45  50
 6 12 18 24 30 36 42 48 54  60
 7 14 21 28 35 42 49 56 63  70
 8 16 24 32 40 48 56 64 72  80
 9 18 27 36 45 54 63 72 81  90
10 20 30 40 50 60 70 80 90 100

BTW, in case you are trying to learn Dyalog APL, I'd recommend having a look at       "Mastering Dyalog APL". And in case you're trying to learn a different dialect, I'd recommend considering to change to Dyalog. (I'm a Dyalog-Fanboy and have made the change myself 20yrs ago. Today Dyalog appears to be practically the only APL-Interpreter that is actively developed and enhanced...)


Q: gtk odd behavior GtkTree append tree_add is called by g_idle_add in another thread
odd behaviour is that the hash is garbage, how would the message digest end up garbled?
the rest of the odd behaviour has been fixed with the below suggestions
#include <pthread.h>
#include <openssl/evp.h>
#include <gcrypt.h>
#include <gtk/gtk.h>

unsigned char *mdSHA256(char *data, size_t *len) {
    unsigned char *md = calloc(33, sizeof(char));
    int mdlen;
    EVP_MD_CTX *mdctx;
    EVP_add_digest(EVP_sha256());
    mdctx = EVP_MD_CTX_create();
    EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL);
    EVP_DigestUpdate(mdctx, data, *len);
    EVP_DigestFinal_ex(mdctx, md, &mdlen);
    EVP_MD_CTX_destroy(mdctx);
    EVP_cleanup();
    *len = mdlen;
    return md;
}

struct peer {
    int approved;
    int port;
    unsigned char *address;
    gcry_sexp_t pubkey;
    struct sf_connection *connection;
    struct peer *next;
    struct peer *prev;
};

struct peer *peers = NULL;

struct peer *peer_new() {
    struct peer *_peer = malloc(sizeof(struct peer));
    if(peers == NULL) {
        _peer->next = _peer;
        _peer->prev = _peer;
        peers = _peer;
    }
    else {
        peers->prev->next = _peer;
        _peer->prev = peers->prev;
        peers->prev = _peer;
        _peer->next = peers;
    }
    return _peer;
}

void *mainthread(void *m) { //code removed so you can run this
    sleep(2);
    struct peer *new_peer = new_peer();
    new_peer->port = 66666;
    new_peer->address = "127.0.0.1";
    new_peer->pubkey = NULL;
    new_peer->approved = 0;
    g_idle_add(tree_add, new_peer);
}

gboolean tree_add(gpointer data) {
    struct peer *new_peer = data;
    GtkTreeIter iter;
    size_t size = gcry_sexp_sprint(new_peer->pubkey, GCRY   SEXP_FMT_ADVANCED, NULL, 0);
    char *buf = malloc(size);
    gcry_sexp_sprint(new_peer->pubkey, GCRYSEXP_FMT_ADVANCED, buf, size);
    unsigned char *md = mdSHA256(buf, &size);
    gtk_tree_store_append(serverstore, &iter, NULL);
    gtk_tree_store_set(serverstore, &iter,
                   COL_IP, new_peer->address,
                   COL_PORT, new_peer->port,
                   COL_PUBKEYMD, md,
                   COL_APPROVED, new_peer->approved,
                   -1);
    free(buf);
    free(md);
    return 0;
}

GtkWidget *setup_tree() {
    GtkWidget *tree;
    GtkTreeViewColumn *column;
    GtkCellRenderer *renderer;

    serverstore = gtk_tree_store_new(N_COLUMNS,
                                 G_TYPE_STRING,
                                 G_TYPE_INT,
                                 G_TYPE_STRING,
                                 G_TYPE_BOOLEAN);

    tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(serverstore));
    g_object_unref(G_OBJECT(serverstore));

    renderer = gtk_cell_renderer_text_new();
    column = gtk_tree_view_column_new_with_attributes("IP", renderer, "text", COL_IP, NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);

    renderer = gtk_cell_renderer_text_new();
    column = gtk_tree_view_column_new_with_attributes("Port", renderer, "text", COL_PORT, NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);

    renderer = gtk_cell_renderer_text_new();
    column = gtk_tree_view_column_new_with_attributes("PubKey", renderer, "text", COL_PUBKEYMD, NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);

    renderer = gtk_cell_renderer_toggle_new();
    column = gtk_tree_view_column_new_with_attributes("Approved", renderer, "active", COL_APPROVED, NULL);
    gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);

    return tree;
}

void on_window_main_destroy() {
    raise(SIGINT);
    gtk_main_quit();
}

int main(int argc, char **argv) {
    GtkWidget *window;
    GtkWidget *view;

    pthread_t main_thread;
    if(pthread_create(&main_thread, NULL, mainthread, NULL)) {
        fprintf(stderr, "Error creating thread\n");
        return 1;
    }

    gtk_init(&argc, &argv);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    g_signal_connect(window, "destroy", on_window_main_destroy, NULL);
    gtk_window_set_title(GTK_WINDOW(window), "ProjXverse Master");
    gtk_window_set_default_size(GTK_WINDOW(window), 640, 480);
    view = setup_tree();
    gtk_container_add(GTK_CONTAINER(window), view);
    gtk_widget_show_all(window);
    gtk_main();

    pthread_join(main_thread, NULL);

    return 0;
}

to make
gcc -c main.c -o test `pkg-config --cflags --libs gtk+-3.0` -lcrypto -lgcrypt -lpthread


Q: File download fails with AFNetworking and other frameworks. wifi goes to sleep automatically - objective c I'm downloading files with AFNetworking framework. File downloads well in foreground mode. But when I put my app to background, WiFi goes to sleep automatically after 10 minutes, by iOS, and my AFNetworking request loses connection. In my AppDelegate I have this code to run background task:
-(void) runBackgroundTask
{
   if (bgTaskId!=UIBackgroundTaskInvalid)
     [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];

     UIBackgroundTaskIdentifier newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
     [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
     [self runBackgroundTask];
}];
   bgTaskId = newTaskId;
}

How disable automatic WiFi sleep? If I run music on my app and downloading file - everything is OK. WiFi doesn't disable.
How I can solve this problem?


Q: jquery toggling all divs instead of just one I have a bunch of div that I am going to toggle upon click. However, I do not want to have a bunch of different jquery functions to accomplish the same thing. The problem is that my current function will toggle all of the divs as opposed to just the selected one. Any solutions for toggling only the one that is selected without having a bunch of jquery functions?
JSFIDDLE
HTML:

     Hello

        Hello Hello Hello

     Hello

        Hello Hello Hello

CSS:
.help-info {
    background: #f1f1f1;
    width: 650px;
    margin: 0 auto;
    padding: 15px 20px;
    font-family: 'Open Sans', serif;
}
.help-info-open {
    background: #1795db;
    width: 650px;
    margin: 0 auto;
    padding: 15px 20px;
    font-family: 'Open Sans', serif;
}
.help-info-link {
    color: #5c5c5c;
}
.help-info-link-open {
    color: #ffffff;
}
.help-info-text {
    background: #fff;
    font-family: 'Open Sans', serif;
    color: #5c5c5c;
    width: 650px;
    margin: 0 auto;
    padding: 15px 20px;
    box-shadow: 0px 1px 2px 0px rgba(0,0,0,0.2);
    -moz-box-shadow: 0px 1px 2px 0px rgba(0,0,0,0.2);
    -webkit-box-shadow: 0px 1px 2px 0px rgba(0,0,0,0.2);
    -o-box-shadow: 0px 1px 2px 0px rgba(0,0,0,0.2);
}

JQUERY:
$(".help-info-link").click(function(event){
    event.preventDefault();
    $('.help-info').toggleClass('help-info-open');
    $('.help-info-link').toggleClass('help-info-link-open');
    $('.help-info-text').toggle();
});

A: Inside the event handler, this refers to the clicked element. So you can do something like this:
$(".help-info-link").click(function(event){
    event.preventDefault();
    $(this).closest('.help-info').toggleClass('help-info-open');
    $(this).toggleClass('help-info-link-open');
    $(this).closest('.help-info').next('.help-info-text').toggle();
});

See here: http://jsfiddle.net/4q6b0gn4/

A: Instead of closest you could use the direct parent function, and a next function like i've done here:
http://jsfiddle.net/uq6xcdo5/1/
$(".help-info-link").click(function(event){
    event.preventDefault();
    $(this).parent().toggleClass('help-info-open');
    $(this).toggleClass('help-info-link-open');
    $(this).parent().next(".help-info-text").toggle();
});


Q: Dynamically instancing a class then deleting it right away? I created my own class but when I try to instantiate it I run into a wall.
Here's my code:
m_interpolation = new Interpolation(m_mesureList, width, height, parent);
delete m_interpolation;

Which generates the error:

Heap block at 0B3E9E40 modified at 0B3E9E68 past requested size of 20

I don't see what I'm doing wrong...
For information here is the full definition of my class Interpolation.h and Interpolation.cpp if that's of any help.
Added a destructor but still didn't fix the problem.
Interpolation::~Interpolation()
{
    delete m_progress;
    m_progress = 0;
}

A: In the ctor:
Populating m_w: up to (m_N-1)
for (int i(0); i < m_N; ++i)
{
    m_pt.push_back(QPointF(mesureList[i]->getX(), mesureList[i]->getY()));
    m_w.push_back(mesureList[i]->getAngle());
}

Later: accessing m_w[m_N], beyond the end of the vector
for (i = m_N; i >= 0; --i)
{
    sum = m_w[i];
    for (j = i+1; j < m_N; j++) sum -= LU[i][j]*m_w[j];
    m_w[i] = sum / LU[i][i];
}

A: Something inside the constructor Interpolation::Interopolation() or the destructor Interpolation::~Interpolation() is writing beyond the size of the object.


Q: Change date format of pandas column (month-day-year to day-month-year) Got the following issue.
I have an column in my pandas with some dates and some empty values.
Example:
    1 - 3-20-2019
    2 -
    3 - 2-25-2019

etc
I want to convert the format from month-day-year to day-month-year, and when its empty, i just want to keep it empty.
What is the fastest approach?
Thanks!

A: One can initialize the data for the days using strings, then convert the strings to datetimes. A print can then deliver the objects in the needed format.
I will use an other format (with dots as separators), so that the conversion is clear between the steps.

Sample code first:
import pandas as pd
data = {'day': ['3-20-2019', None, '2-25-2019'] }
df = pd.DataFrame( data )

df['day'] = pd.to_datetime(df['day'])
df['day'] = df['day'].dt.strftime('%d.%m.%Y')
df[ df == 'NaT' ] = ''

Comments on the above.
The first instance of df is in the ipython interpreter:
In [56]: df['day']
Out[56]:
0    3-20-2019
1         None
2    2-25-2019
Name: day, dtype: object

After the conversion to datetime:
In [58]: df['day']
Out[58]:
0   2019-03-20
1          NaT
2   2019-02-25
Name: day, dtype: datetime64[ns]

so that we have
In [59]: df['day'].dt.strftime('%d.%m.%Y')
Out[59]:
0    20.03.2019
1           NaT
2    25.02.2019
Name: day, dtype: object

That NaT makes problems. So we replace all its occurrences with the empty string.
In [73]: df[ df=='NaT' ] = ''

In [74]: df
Out[74]:
          day
0  20.03.2019
1
2  25.02.2019

A: Not sure if this is the fastest way to get it done. Anyway,
df = pd.DataFrame({'Date': {0: '3-20-2019', 1:"", 2:"2-25-2019"}}) #your dataframe
df['Date'] = pd.to_datetime(df.Date) #convert to datetime format
df['Date'] = [d.strftime('%d-%m-%Y') if not pd.isnull(d) else '' for d in df['Date']]

Output:
         Date
0  20-03-2019
1
2  25-02-2019


Q: Move 50,000 selected emails (not all) from one IMAP folder to another on same server? I use an IMAP mail folder that contains 80,000 messages, and I'd like to move a selected subset of ~50,000 messages (all the messages dated in 2020) to another folder on the same IMAP server. Can this be scripted from the Linux command line on the client computer (not on the IMAP server computer)? Fetchmail? Movemail? Anything?
Also same question for deletion: is there a way to select (say) 50,000 emails from 2018 in an IMAP mail folder and delete them, via Linux command line tools?
Note: The server is outlook.com (Office 365) if it matters. I tried using Outlook (GUI) for this operation, but it can't even select "all emails from year" in any efficient way. I also tried Thunderbird with Owl to speak Exchange, and even though I can select the emails, the big move simply doesn't occur. A scripting approach is the latest attempt.
Thank you!

A: I recently found myself having to automatically move messages on an IMAP server from one folder to another.
To do this reliably, I wrote a script which I call imap-helper. It connects to an IMAP server and moves messages matching a given query string between two folders. It uses Mail::IMAPClient which is supplied by a package (perl-mail-imapclient) in my distribution (Arch).
In my coment on the original post I suggested using gnutls-cli to connect to your IMAP server; I still recommend doing this to get a grasp of what's happening behind the scenes (and so you can debug your query syntax more quickly). Here's an example raw IMAP session just for reference, but the script that follows it should be better suited for your problem.

*

*(The tool rlwrap provides GNU Readline editing and history to the interaction)
  $ rlwrap -S "> " gnutls-cli imap.mail.yahoo.com -p 993
  > A LOGIN myusername mypassword
  A OK LOGIN completed
  > A LIST "" *           # List all the folders on the server
  * LIST (\HasNoChildren) "/" "ALL"
  * LIST (\Junk \HasNoChildren) "/" "Bulk Mail"
  * LIST (\HasNoChildren) "/" "Inbox"
  ...
  A OK LIST completed
  > A SELECT Inbox
  * 12 EXISTS
  * 0 RECENT
  ...
  A OK [READ-WRITE] SELECT completed; now in selected state
  > A SEARCH BEFORE 01-Jan-2021
  * SEARCH 11 12
  A OK SEARCH completed
  > A MOVE 11,12 "Bulk Mail"
  * OK [COPYUID 1609256255 58:59 57:58]
  ...
  A OK MOVE completed

As for the script, I have tested it on my Gmail Inbox which has 13000 messages. I moved them all from INBOX to INBOX2 (which Gmail created automatically). This took a couple of minutes. Then I moved them back again. I'd be glad to hear if it works on your server.
For your case what you'd do is first create a file called ~/.imap-creds.pl with your server, username, and password.
Then you'd run something like
$ imap-helper outlook FOLDER1 'SINCE "01-Jan-2019" BEFORE "01-Jan-2020"' FOLDER2 -e

to move all messages in FOLDER1 that were received in 2019, into FOLDER2. The user interface is designed so that you can build the command one argument at a time:
$ imap-helper         # lists accounts from config file
gmail
...
$ imap-helper gmail   # lists folders in the gmail account
INBOX
Personal
Receipts
...
$ imap-helper gmail INBOX   # lists messages in INBOX
...
etc.

Here is the script:
#!/usr/bin/perl
# 21 Jan 2021
use warnings;
use strict;
use open (":encoding(UTF-8)", ":std" );

use Mail::IMAPClient;

use Data::Dumper;
$Data::Dumper::Indent=0;
$Data::Dumper::Purity=1;
$Data::Dumper::Terse=1;

use Getopt::Long;
Getopt::Long::Configure ("bundling", "no_ignore_case");

use Carp;
$SIG{__DIE__} = sub {
    my $error = shift;
    Carp::confess "Error: ";
};

# change the help text if you change this
my $credfn=glob("~/.imap-creds.pl");

my($bad_args, $help, $verbose, $execute, $max, $zero_results_ok);
GetOptions('-h|help' => \$help,
           '-v|verbose' => \$verbose,
           '-e|execute' => \$execute,
           '-z|zero-results-ok' => \$zero_results_ok,
           '-m|max=f' => \$max
    ) or $bad_args = 1;

my ($action);

my ($acct, $src, $dst, $query);

sub verb {
  warn "imap-helper: ",@_,"\n" if $verbose;
}

if(@ARGV>4) {
  warn "Expected 4 arguments but you passed ".scalar(@ARGV);
  $bad_args = 1;
} elsif(@ARGV==4) {
  $action = "move";
} elsif(@ARGV==3) {
  $action = "search";
} elsif(@ARGV==2) {
  $action = "list";
} elsif(@ARGV==1) {
  $action = "folders";
} elsif(@ARGV==0) {
  $action = "accounts";
}
($acct,$src,$query,$dst) = @ARGV;

sub usage {
   "Usage: imap-helper [-h | -v | -e | -z] ACCOUNT SRC_FOLDER QUERY DST_FOLDER\n";
}
sub help {
  q{
Options:
-h --help     print this message
-v --verbose  be verbose
-e --execute  execute the move
-z --empty-search-ok   exit 0 on empty search (for scripts)

By default no messages are moved, pass -e to execute the move.

Configuration: ~/.imap-creds.pl
Config syntax: [ SERVER_NAME => { Server => "HOST",
    User     => "USER",
    Password => "PASS"
  }, ... ]

With zero arguments, lists accounts. With only the ACCOUNT argument,
lists folders on ACCOUNT. With SRC_FOLDER argument, list contents of
SRC_FOLDER. With QUERY argument, list results of QUERY. With
DST_FOLDER argument, plan a move of messages matching QUERY from
SRC_FOLDER to DST_FOLDER. Pass "-e" to execute the move.

QUERY is an IMAP query, like "ALL" or 'BEFORE "15-Jan-2021"' (dates must
be in this exact format). Other keywords include TO, CC, FROM,
SUBJECT, TEXT; AND, OR, NOT; LARGER, SMALLER; NEW, RECENT, SEEN,
ANSWERED. See <https://tools.ietf.org/html/rfc3501> for a full list.
IMAP queries can be combined, for example:

$ imap-helper gmail INBOX 'SINCE "01-Jan-2020" BEFORE "01-Jan-2021"'
# (lists all INBOX messages from 2020)

This tool uses MOVE which is not part of the original IMAP RFC but
which should be well supported.

Example interaction:

$ cat .imap-creds.pl
[ yahoo =>
  { Server   => 'imap.mail.yahoo.com',
    User     => 'napoleon',
    Password => 'MYPASSWORD123'
  },
  gmail => ...
]
$ imap-helper
yahoo
gmail
$ imap-helper yahoo
ALL
Archive
Inbox
...
$ imap-helper yahoo Inbox
48    19 Jan 2021  XXXXX@yahoo.com           YYYYY@gmail.com           test 2
...
$ imap-helper yahoo Inbox "BEFORE 15-Jan-2021"
50    29 Dec 2020  XXXXX@yahoo.com           YYYYY@yahoo.com           test 1
...
$ imap-helper yahoo Inbox "BEFORE 15-Jan-2021" Archive -e -v -z
imap-helper: Connecting to server imap.mail.yahoo.com as XXXXX
imap-helper: Searching for BEFORE 15-Jan-2021
imap-helper: Found 1 matches for BEFORE 15-Jan-2021
imap-helper: Moving 1 messages

};
}

if($bad_args) { print STDERR usage; exit(1) }
if($help) {
  my $pager = $ENV{PAGER};;
  open STDOUT, "| $pager" or warn "Not paging STDOUT: $!\n" if defined $pager;
  print (usage, help);
  close(STDOUT); wait(); exit(0);
}

die "Shouldn't get here" if !defined $action;

################################################################
## LOGIN

if(!-e $credfn) {
  die "Missing credential file $credfn\n";
}
my $creds = eval `cat $credfn`;
#verb (Dumper($creds));

ref $creds eq "ARRAY" or die "Expected an array: $credfn\n".
    "Got: ".(Dumper($creds))."\n";

if($action eq "accounts") {
  # no account specified, just list them all
  verb "Listing accounts from $credfn\n";
  my $ind = 0;
  my @accts = grep {!($ind++ % 2)} (@$creds);
  print "$_\n" for(@accts);
  exit(0);
}

my %creds = @$creds;

my $srvcr = $creds{$acct};
if(!defined $srvcr) {
  die "Account $acct not found in $credfn\n";
}

verb "Connecting to server $srvcr->{Server} as $srvcr->{User}";

my $imap = Mail::IMAPClient->new(
  Server   => $srvcr->{Server},
  User     => $srvcr->{User},
  Password => $srvcr->{Password},
  Ssl      => 1,
  Uid      => 1,
    ) or die "Could not connect to $srvcr->{Server} as $srvcr->{User}\n";

if($action eq "folders") {
  my $folders = $imap->folders
      or die "Error listing folders: ", $imap->LastError, "\n";
  print join("\n",@$folders),"\n";
  exit(0);
}

$imap->select( $src )
    or die "Select $src error: ", $imap->LastError, "\n";

# Truncate a string $s to width $w, for use in a table
sub trunc {
  my ($s, $w) = @_;
  $s = "" if !defined($s);
  if(ref $s eq "ARRAY") {
    $s = join(",",@$s);
  }
  my $l = length($s);
  my $o;
  if($l>=$w) {
    $o = substr($s,0,$w-3)."...";
  } else {
    $o = $s.(" "x($w-$l));
  }
  return $o;
}

sub show_msgs {
  my @msgs = @_;
  # this should but doesn't work (as first argument to parse_headers)
#  my $r = $imap->Range(@msgs);

  my $heads = $imap->parse_headers(\@msgs, "Date", "Subject", "To", "From");
#  for my $msg (sort {$a <=> $b} (keys %$heads)) {
  for my $msg (@msgs) {
    my $hs = $heads->{$msg};
    my $date = $hs->{Date}->[0]||"";
    # remove weekday and HH:MM:SS from date
    $date =~ s/^\D+,\s*//;
    $date =~ s/ \d\d:.*$//;
    print trunc($msg,7)," ",
        trunc($date,12)," ",
        trunc($hs->{To},25)," ",
        trunc($hs->{From},25)," ",
        trunc($hs->{Subject},25),
        "\n";
  }
}

if($action eq "list") {
  my @msgs = $imap->messages;
  if(defined($max) && @msgs>$max) { @msgs = @msgs[0..($max-1)]; }
  show_msgs(@msgs);
  exit(0);
}

verb "Searching for $query";
my @msgs = $imap->search($query);
if(!@msgs) {
  if(!$zero_results_ok) {
    die "Error or no matches for $query ",$imap->LastError,"\n";
  } else {
    verb "No matches found for $query";
    exit 0;
  }
}
verb "Found ".(@msgs)." matches for $query";
if(defined $max && @msgs > $max) { @msgs = @msgs[0..($max-1)]; }

if($action eq "search") {
  show_msgs(@msgs);
  exit(0);
}

if($action eq "move") {
  verb "Moving ".(@msgs)." messages";
  my $msgstr=join(",",@msgs);
  if(!$execute) {
    warn "Would have moved $msgstr from $src to $dst\n";
    warn "Pass -e to execute move\n";
  } else {
    $imap->move($dst,$msgstr)
        or die "Could not move messages\n";
  }
  exit(0);
}

die "Something wrong";


Q: Why am I *not* getting this warning: "variable masks earlier declaration"? Here's my entire script, crafted to include two variable with the same name, one of which is masking the other:
#!/usr/bin/env perl
use strict;
use warnings;

my $hi = "First hi";
print "$hi\n";

{
    my $hi = "Second hi";
    print "$hi\n";
}

print "$hi\n";

If I run this script, I get this output, and noticeably no warnings:
First hi
Second hi
First hi

If I remove the curly braces around the second $hi variable so that is in the same scope as the first $hi variable, I get this warning:
"my" variable $hi masks earlier declaration in same scope at hi.pl

However, I want this warning even when the variable is not in the same scope. I want the warning every time a variable name is shadowing another. How can I enable this warning? Is there a Perl Critic policy that I can enable that will warn me about this?

A: Did you try this:
Perl::Critic::Policy::Variables::ProhibitReusedNames;


Q: WPF Datagrid does not fill the entire height and width when maximizing window My DataGrid is not taking the whole space when I maximize the window in my WPF application. This is how I created the layout:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Grid Grid.Row="0" Grid.Column="0" Width="265">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="Date From:" />
        <Label Grid.Row="1" Grid.Column="0" Content="Date To:" />
        <DatePicker Grid.Column="1" Grid.Row="0" Margin="3" x:Name="DateFrom" />
        <DatePicker Grid.Column="1" Grid.Row="1" Margin="3" x:Name="DateTo" />
        <Button Grid.Column="1" Grid.Row="2" HorizontalAlignment="Right"
                        MinWidth="80" Margin="3" Content="Send" Click="PopulateGrid"  x:Name="BtnPopulateGrid"/>
    </Grid>

    <StackPanel Grid.Row="0" Grid.Column="1">
        <DataGrid Width="Auto" x:Name="Grid" Height="553"
                  Padding="10 0 0 0" VerticalScrollBarVisibility="Visible" Margin="10,0,-707,0" />
    </StackPanel>
</Grid>

and this is how it looks like on regular size:

and this is how it looks like when window is max:

What can I try next? I am new to WPF.

A:     <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid Grid.Row="0" Grid.Column="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="200" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>

            <Label Grid.Row="0" Grid.Column="0" Content="Date From:" />
            <Label Grid.Row="1" Grid.Column="0" Content="Date To:" />
            <DatePicker Grid.Column="1" Grid.Row="0" Margin="3" x:Name="DateFrom" />
            <DatePicker Grid.Column="1" Grid.Row="1" Margin="3" x:Name="DateTo" />
            <Button Grid.Column="1" Grid.Row="2" HorizontalAlignment="Right" MinWidth="80" Margin="3" Content="Send" Click="PopulateGrid"  x:Name="BtnPopulateGrid"/>
        </Grid>

        <Grid Grid.Row="0" Grid.Column="1">
            <DataGrid x:Name="Grid" Padding="10 0 0 0" VerticalScrollBarVisibility="Visible" />
        </Grid>
    </Grid>

Firstly if you wanna make your datagrid fill a container automatically, you need to use Grid, not StackPanel also your datagrid sizes need to be set auto.
Edit:
As @Erjon said : You don't have to use a container when you have a single DataGrid.But if you have more components with your DataGrid, Grid will be a better container choice instead of StackPanel.
Your main GridDefination sizes were set as Auto, that was wrong.You need to work with "*" if you want a resposive design.Auto means that "Set this control's size with its children".

A: Try adding in the datagrid ColumnWidth="*"
It will expand all columns to avaiable space and the datagrid will fill it's parent
The second ColumnDefinition of the first grid should be <ColumnDefinition Width="*" />
And as @Zacos said in my answers comment you have to remove Width


Q: Using rails3-jquery-autocomplete from a nested form I receive this error when I type an existing topic into the topic field of my form:
Started GET "/posts/autocomplete_topic_name?term=test" for 127.0.0.1 at 2011-05-21 10:51:19 -0700
  Processing by PostsController#show as JSON
  Parameters: {"term"=>"test", "id"=>"autocomplete_topic_name"}
  Post Load (0.2ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = 0 LIMIT 1
Completed   in 28ms

ActiveRecord::RecordNotFound (Couldn't find Post with ID=autocomplete_topic_name):
  app/controllers/posts_controller.rb:9:in `show'

Rendered /home/dude/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.5ms)
Rendered /home/dude/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (4.2ms)
Rendered /home/dude/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (14.2ms)

The topics "test" and "testing" exist.
models:
class Topic < ActiveRecord::Base
  has_many        :posts
  validates       :name, :presence => true,
  attr_accessible :name, :post_id
end

class Post < ActiveRecord::Base
  belongs_to :topic
  accepts_nested_attributes_for :topic
  attr_accessible :name, :title, :content, :topic, :topic_attributes
end

view:
/posts/new renders only this form: (uses simple_form)
<%= simple_form_for :post, :url => { :controller => :posts, :action => "create" } do |f| %>

Create a Post

  <%= f.input :name, :label => false, :placeholder => "Name (optional)", :required => false %>
  <%= f.input :title, :label => false, :placeholder => "Title" %>
  <%= f.input :content, :label => false, :placeholder => "Content", :as => :text %>
  <%= f.simple_fields_for :topic do |topic_form| %>
    <%= topic_form.input :name, :label => false, :placeholder => "Topic", :url => autocomplete_topic_name_path, :as => :autocomplete %>
  <% end %>
  <%= raw recaptcha_tags -%>
  <%= f.button :submit, "Post" %>
<% end %>

controller:
class PostsController < ApplicationController
  autocomplete :topic, :name, :full => true
  respond_to :html, :js, :xml

  def new
    @post = Post.new
  end

  def create
    topic_name = params[:post].delete(:topic)
    @topic = Topic.find_or_create_by_name(topic_name)
    @post = Post.new(params[:post])
    @post.topic = @topic
    respond_to do |format|
      if verify_recaptcha(:model => @post) && @post.save
        format.html { redirect_to(@post, :notice => 'Post was successfully created.') }
      else
        flash.delete(:recaptcha_error)
        flash.now[:error] = "Incorrect word verification. Are you sure you\'re human?"
        format.html { render :action => "new" }
      end
    end
  end
end

Line 9 of the Posts controller is:
 @post = Post.find(params[:id])

in the posts#show
routes.rb:
MyApp::Application.routes.draw do
  root :to => "posts#index"
  resources :topics
  resources :posts
  resources :comments
  match "posts/autocomplete_topic_name", :as => "autocomplete_topic_name"
end

Here's my gemfile:
gem 'rails', '3.0.6'
gem 'sqlite3'

gem 'ancestry'
gem 'jquery-rails', '>= 1.0.3'
gem 'kaminari'
gem 'nifty-generators'
gem 'rdiscount'
gem 'rails3-jquery-autocomplete'
gem 'recaptcha', :require => 'recaptcha/rails'
gem 'simple_form'

and schema:
create_table "posts", :force => true do |t|
  t.string   "name"
  t.string   "title"
  t.text     "content"
  t.integer  "topic_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "topics", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
end

Thanks for taking a look.

A: Within your routes file, try moving the "match 'posts/...'" line before "resources :posts".


Q: C# WinFormApp DataGridView cannot show object inside of List UPD: I have found this article: http://www.developer-corner.com/blog/2007/07/19/datagridview-how-to-bind-nested-objects/ , but it is pretty old, posted in 2007.
I have C# win forms app and I want to show list of items in datagridView:
here is the List: `
public static List<Item> ItemsList { get; set; } = new List<Item>()
        {
            new Item()
            {
                Id = 1,
               ItemName = "Ice Tea",
               ItemCategory   = new Category(){
                    Name = "Drinks"
                },
                Price = 4000.00,
        },...}`

as  you can see I have another object ItemCategory inside Item.
Here is the code to connect to dataGrid:
dataGridAllProducts.DataSource = Item.ItemsList;

The problem is that I cannot get the Name from ItemsList and show in rows, here is what it shows in output:
As you can see instead of Drinks it shows another thing.
Also i tried to loop through my list using foreach and rows to datagrid but it throwed some errors .

A: On class Category add this code:
public override string ToString(){
    return this.Name;
}

When you call the object on need a string, the object Category show Name property.

A: The column binding for the data grid view might not be right.
Please try the following in the design view:
1. Right click on your data grid view and select "Edit Columns"
2. Select the column for which the data is not coming right.
3. In the "DataPropertyName" under "Data" mention "Name" i.e. the property name of your Item class.


Q: Building a partial state inside an action to update a REST API I have a bound action:
updateAge(age)

Part of my state is this:
//user data
user {
   name: 'foo',
   age: 10
}

In my action creator, can I do something like this?
export const updateAge = (age) => (dispatch, getState) => {
   let currentState = { ...getState().user, age }
   dispatch(updateUser(currentState)) //updates API
}

This would save work on my back end as I would just have one route handling all user updates.
router.post('/user'....)

As long as I make sure only one fetch/post happens at any given time, is this a good pattern?  What are the pros and cons?


Q: Repair Presentation Error with chart.replace_data() I used  the chart.replace_data() to replace the old category labels with the new ones.  When I opened the output presentation, I saw the message to repair the presentation and when I clicked the repair button, all the data of the presentation are gone. Here's my code:
from pptx.enum.chart import XL_CHART_TYPE
from pptx import Presentation
#from pptx.chart.data import CategoryChartData
from pptx.chart.data import ChartData
from google_trans_new import google_translator
trans=google_translator()
proj1 = Presentation("C:/Users/naych/Documents/chart.pptx")

rev_lbl=[]

for slide in proj1.slides:
    for shape in slide.shapes:
        if shape.has_chart:
            chart=shape.chart
            if chart.chart_title.has_text_frame:
                chart_title_str=chart.chart_title.text_frame.text
                rev=trans.translate(chart_title_str,lang_tgt='ja')
                chart.chart_title.text_frame.text=rev

            print(shape.name)
            chart_data=ChartData()
            for category in chart.plots[0].categories:
                cat_lbl=category.label
                rev_lbl.append(trans.translate(cat_lbl,lang_tgt='ja'))
            chart_data.categories=rev_lbl

chart.replace_data(chart_data)

proj1.save('chart_lang.pptx')

I am very happy if you help me to fix it. Please! Thank you.