text:
Q: set firebase data in textfield flutter dart What I want to do :
When the user want to change their name on app,
User going to modify :
when the user showing this screen, already enter his name in this textfiled. He can change it.
Example:
In the picture,
the user going to modify his username
His firebase username is "default". It's already typed.
he remove "t" and submit.

My code here
 class ModifyScreen extends StatefulWidget {
      final String uid;
      const ModifyScreen({
        super.key,
        required this.uid,
      });

      @override
      State<ModifyScreen> createState() => _ModifyScreenState();
    }

    class _ModifyScreenState extends State<ModifyScreen> {
      var userData = {};
      bool isLoading = false;

      @override
      void initState() {
        getData();
        super.initState();
      }

      getData() async {

        try {
          var userSnap = await FirebaseFirestore.instance
              .collection('users')
              .doc(widget.uid)
              .get();

          userData = userSnap.data()!;
          setState(() {});
        } catch (e) {
          showSnackBar(
            context,
            e.toString(),
          );
        }

      }

      @override
      Widget build(BuildContext context) {
        TextEditingController _namecon = TextEditingController();
        return Scaffold(
                body: Padding(
                  padding: const EdgeInsets.all(18),
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        TextField(
                          controller: _namecon,
                          decoration:
                              InputDecoration(hintText: userData['username']),
                        )
                      ],
                    ),
                  ),
                ),
              );
      }
    }

A: Remove decoration and add _namecon.text = userData['username'] in build, also take TextEditingController _namecon = TextEditingController() outside of build


text:
Q: How to make synchronous forEach loop and make an Asynchronous request to an API in Javascript Am trying to make an API using an array of parameters and use then use the value to make another API call to get another array. using javascript but am hitting the sand with my back every time.
var axios = require('axios');
var otp= [
  'bitcoin', 'cat', 'orange', 'mango', 'bats', 'california'
];
optDetails = [];
const promises = otp.map(info => axios.get(`https://www.iot.com/api/?query=${info}`).then(res => res.data));

const newPromise = Promise.all(promises).then(stateData => {
    optDetails.push(stateData)
    optDetails.map(nextData => axios.get(`https://www.crypto.com/api/?query=${nextData.uuid}`).then(res => res.data))
});

Promise.all(newPromise).then((res) => {
    console.log(res)
}, err => console.log(err));

But I get this error
TypeError: undefined is not a function
    at Function.all (<anonymous>)
    at Object.<anonymous> (/home/runner/index.js:13:9)
    at Module._compile (internal/modules/cjs/loader.js:654:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
    at Function.Module._load (internal/modules/cjs/loader.js:498:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:695:10)
    at startup (internal/bootstrap/node.js:201:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:516:3)

A: On your second .map(), you're creating another array of promises and you need to return that from the .then() handler and use Promise.all() with that.
The result of optDetails.map() is an array of promises.  You need to use Promise.all() on that and then return that new promise. Change this:
const newPromise = Promise.all(promises).then(stateData => {
    optDetails.push(stateData)
    optDetails.map(nextData => axios.get(`https://www.crypto.com/api/?query=${nextData.uuid}`).then(res => res.data))
});

to this:
const newPromise = Promise.all(promises).then(stateData => {
    optDetails.push(stateData)
    return Promise.all(optDetails.map(nextData => axios.get(`https://www.crypto.com/api/?query=${nextData.uuid}`).then(res => res.data)));
});

newPromise.then((res) => {
    console.log(res)
}, err => console.log(err));

or just get rid of the intermediate newPromise variable entirely:
Promise.all(promises).then(stateData => {
    optDetails.push(stateData)
    return Promise.all(optDetails.map(nextData => axios.get(`https://www.crypto.com/api/?query=${nextData.uuid}`).then(res => res.data)));
}).then((res) => {
    console.log(res)
}, err => console.log(err));

In addition optDetails.push(stateData) looks wrong.  I don't know what your data structures actually are, but stateData itself is an array (as resolved from the previous Promise.all().  Perhaps you mean optDetails = stateData?  Or perhaps you want to concatenate stateData onto what's already in optDetails?

Simpler Version
It seems to me that this results in much simpler code if you changed your multiple loops into one loop.  You still end up with the same array of results.
var axios = require('axios');
var otp = [
  'bitcoin', 'cat', 'orange', 'mango', 'bats', 'california'
];

Promise.all(otp.map(info => axios.get(`https://www.iot.com/api/?query=${info}`).then(res => {
    return axios.get(`https://www.crypto.com/api/?query=${res.data.uuid}`).then(res2 => res2.data);
}))).then(results => {
    console.log(results);
}).catch(err => {
    console.log(err);
});

A: Your newPromise is a promise (created by Promise.all(…).then(…)) for undefined (the return value of the then callback). You'll need to add a return there.
Then you are calling Promise.all on newPromise - but newPromise is not an iterable like an array of promises. Maybe you expected it to be a promise for the array of promises created by optDetails.map(), but even then: you have to call Promise.all right away on the array itself, before returning a promise from the then callback.
You are most likely looking for
var axios = require('axios');
var otp = ['bitcoin', 'cat', 'orange', 'mango', 'bats', 'california'];

const promises = otp.map(info => axios.get(`https://www.iot.com/api/?query=${info}`).then(res => res.data));
const newPromise = Promise.all(promises).then(stateData =>
    Promise.all(stateData.map(nextData => axios.get(`https://www.crypto.com/api/?query=${nextData.uuid}`).then(res => res.data)))
);

newPromise.then((res) => {
    console.log(res)
}, err => {
    console.log(err)
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to restore app's state after preferred language change? I am using SwiftUI (if it matters in this case) and I am interested in my app working on iOS 13 and up.
My app has 2 languages. I have added Settings.bundle file and now I can see PREFERRED LANGUAGE settings for my app. So far so good.
The problem is that when I change the language, app relaunches and resets. I would like to preserve its state.
During one of Apple's WWDC presentation it was said to take this approach (following is text from Apple's slides):

ViewController State Restoration
Changing languages via Settings will relaunch your application Enable
state restoration in your AppDelegate with:
application(_:shouldSaveApplicationState:)
application(_:shouldRestoreApplicationState:)
Set restorationIdentifier on controllers to make language switching
seamless

And this:

Scene State Restoration
Enable state restoration in your SceneDelegate
with:
stateRestorationActivity(for scene:)
Return an NSUserActivity object that encodes your scene state

But those informations are very brief and I don't know how to implement the code from those examples. I have also found this article in Apple's documentation:
https://developer.apple.com/documentation/uikit/uiviewcontroller/restoring_your_app_s_state
But it is way more complicated than those slides from WWDC presentation. In this article they write that there are 2 different approaches: for iOS 13 and up and for 12 and earlier. As I mentioned already, I am only interested in iOS 13 and up. What is the simplest way to make it work?
I did try to find a solution here. And tried to find a tutorial on Google and Youtube. No luck.

A: It appears to me you are looking for a tutorial on SwiftUI and state restoration. Try this one here:
UIScene State Restoration with NSUserActivity and SwiftUI on iOS 13 (iPadOS)
Multi-window support introduces fundamental changes to the life cycle of iOS 13 and iPadOS apps. It's closely connected with the concept of a scene, which represents a single instance of your app's user interface. Every scene has its own life cycle and there can be more than one scene running at the same time.
I am explaining what are scenes and how they are put together in iOS 13 (iPadOS) App Life Cycle with UIScene.
Since the system manages your app scenes, it may connect and disconnect scenes to reclaim their resources. In this case the user interface is gone and will be replaced with a snapshot. The next time the user opens that scene, they will face an initial window with all unfinished work lost.
The solution is per-scene state restoration, which becomes a vital feature for rich user experience beginning from iOS 13 (iPadOS). In this article let's find out how to implement scene-based state restoration with NSUserActivity and SwiftUI.
https://www.vadimbulavin.com/ios13-ipados-uiscene-state-restoration-with-nsuseractivity-and-swiftui/


text:
Q: Redirect Non found sub directory link to home page through .htaccess I have a website like www.example.com and its have some sub directories vol1, vol2,, vol3, .....vol20.
I am facing a issue with Redirect Non found sub directory link to home page through .htaccess.
Suppose when we search/go to any not found url like
www.example.com/vol1/05.pdf
www.example.com/vol13/01-39.pdf
www.example.com/vol3/klsdk

then it not redirect to home page. i have tried below code in htaccess
     # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
        RewriteRule ^(.*)$ /index.php/$1 [L]

Options +Indexes
IndexOptions +FancyIndexing

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{http_host} ^example.com [NC]
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,NC]


text:
Q: javax.el.MethodNotFoundException: Method not found Here is my ManagedBean
package controller;

import java.io.Serializable;
import java.util.List;

import javax.annotation.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

import model.Client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import service.ClientService;

    public class ClientBeanManger implements Serializable {
         private static final long serialVersionUID = 1L;

         @Autowired
         private ClientService clientService;
         private Client client;

        public void init () {
              }

         public Client getClient() {
            return client;
        }

        public void setClient(Client client) {
            this.client = client;
        }

         public void saveClient(Client client){
             clientService .add(client);

         }

I called saveclient method like in :

I have looked lots of examples about jsf .Everybody calls like I have called the method.What is the wrong which I haven't seenn i still not work since 2 days

A: You can try:

A: Try using the action instead of actionListener
like :
Change this

to this


text:
Q: Azure Event Hub: every other connection attempt fails We have Azure 4 subscriptions containing one Event Hub instance each. One of the instances is not responsive, from our application logs:
Jan 05 10:53:10 ERROR CheckFacade - Azure event hub connection failed. EndPoint: sb://xxxx.servicebus.windows.net/, ...
Jan 05 10:53:10 System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Jan 05 10:53:10     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Jan 05 10:53:10     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Jan 05 10:53:10     at Microsoft.Azure.EventHubs.Amqp.AmqpEventHubClient.<CreateConnectionAsync>d__31.MoveNext()
...

1 out 2 times connection attempt fails. Is there any way to see Event Hub logs to tackle this issue?
Note: Azure support recommended to ask this question here.


text:
Q: How To Secure Collapsible / Expandable Frames Dears,
How To Secure Collapsible / Expandable Frames with password.
I have used the Script shared in : https://github.com/PySimpleGUI/PySimpleGUI/issues/295
Here's a reduced part of it, just to clarify my query :
import PySimpleGUI as sg

layout1 = [[sg.Text('This is layout 1 - It is all Checkboxes')],
       *[[sg.CB(f'Checkbox {i}')] for i in range(3)]]

layout2 = [[sg.Text('This is layout 2')],
       [sg.Input(key='-IN-')],
       [sg.Input(key='-IN2-')]]

layout = [[sg.Column(layout1, key='-COL1-'), sg.Column(layout2, visible=False, key='-COL2-')],
      [sg.Button('1'), sg.Button('2'), sg.Button('Exit')]]

window = sg.Window('Swapping the contents of a window', layout)

while True:
   event, values = window.read()
   print(event, values)
   if event in (sg.WIN_CLOSED, 'Exit'):
       break
   elif event in '123':
       window[f'-COL{layout}-'].update(visible=False)
       layout = int(event)
       window[f'-COL{layout}-'].update(visible=True)
window.close()

What should be the event to be added , so that , once we click on Button "2" , it will ask for User/Password to be able to access inside that frame. Thanks in advance


text:
Q: Knitr: Turning the R chunk figure caption 90 degrees inline Latex Here is my a code to demo what I cannot do. I use an R chunk to make a figure and use out.extra='angle=90' to make the figure post sideways on the page.  Now how do I get my caption to go sideways too?
\documentclass{article}
\usepackage{subcaption}
\begin{document}

<<test-plot,echo=FALSE,fig.cap="I would like to be posted sideways under figure, NOT HERE",out.extra='angle=90'>>=
plot(1)
abline(0, 1)
plot(rnorm(10))
for(i in 1:10) {
    abline(v = i, lty = 2)
}
@
\end{document}


text:
Q: How to enable the "Tags & Notes" tab inside my enterprise wiki I am working on a publishing site of type enterprise wiki , but currently the "Tags & Notes" icon is displayed.  As follow:-

And it mentioned that I might not have the permission, although I am the site administrator and part of the contributor group .
Can anyone advice on this please?
Thanks


text:
Q: video streaming using customtkinter How to video streaming using customtkinter library in class method form ?
i was troubling to configure how to that, i see many examples but i dont know how to implement this on my code
# code for video streaming
def camera(self):
    ret, img = cap.read()
    cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)
    img = Image.fromarray(cv2image)
    ImgTks = ImageTk.PhotoImage(image=img)
    self.camera.imgtk = ImgTks
    self.camera.configure(image=ImgTks)
    self.after(20,self.camera)

if __name__ == "__main__":
    app = TimeIn()
    app.camera()
    app.mainloop()

this is my whole code for this
https://github.com/Fsociety-Mrn/videostreamingCutsomkinter
please do help me i am new to this

A: The main issue is that you have used same name camera for a label and a function.  Just rename the function to other name, for example streaming():
...
class TimeIn(customtkinter.CTk):
    ...
    # code for video streaming
    def streaming(self):
        ret, img = cap.read()
        cv2image= cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2RGB)
        img = Image.fromarray(cv2image)
        ImgTks = ImageTk.PhotoImage(image=img)
        self.camera.imgtk = ImgTks
        self.camera.configure(image=ImgTks)
        self.after(20, self.streaming)

if __name__ == "__main__":
    app = TimeIn()
    app.streaming()
    app.mainloop()

A: Using tkinter_webcam module:-
import tkinter as tk
from tkinter_webcam import webcam

window = tk.Tk()  # Sets up GUI
window.title("Example")  # Titles GUI
window.geometry("1000x1000")  # Sizes GUI

# Uses Box class from webcam to create video window
video = webcam.Box(window, width=450, height=450)
video.show_frames()  # Show the created Box

tk.mainloop()


text:
Q: Installing/building git-svn for RHEL 6 I do not have access to the RHEL6 repo, so what wouold be the best approach to building and/or installing the git-svn tool on RedHat Enterprise Linux 6?

Managed to install git & git-svn 1.7.9 by uninstall the existing one (yum erase git) and make installing the latest one from source. Worked on 64-bit too.

A: A possible solution would be to rebuild locally (ie in a directory within your home directory) everything:

*

*git and its dependencies

*svn and its dependencies

*perl and ruby (used by git-svn script)

You can try my GitHub project compileEverything:
(it will download and compile for you all the necessary sources: no configuration required)
cd ~
bash # (you need a bash session)
# set your http_proxy/https_proxy if needed
wget --no-check-certificate https://github.com/VonC/compileEverything/tarball/master
tar xpvf master
cd compil*
./maken-env.sh -title=test
# wait 4 hours
source .bashrc -force # special bash with all the right local path

git and git-svn will then work.


text:
Q: How to enable Ad Hoc Distributed Queries When I run a query with OPENROWSET in SQL Server 2000 it works.
But the same query in SQL Server 2008 generates the following error:

SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure

A: If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:
EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO

A: sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

A: The following command may help you..
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO

A: You may check the following command
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO  --Added
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
     'SELECT GroupName, Name, DepartmentID
      FROM AdventureWorks2012.HumanResources.Department
      ORDER BY GroupName, Name') AS a;
GO

Or this documentation link


text:
Q: In Xcode, how do I know which class implement a protocol? I am wondering in Xcode, can I quickly know which classes implement some protocols?
I don't want to use search, but want to quickly identify such classes.

A: in particular class in which protocol implement just press
 'command btn + right click of mouse' on protocol method..
it will show list of all class with implementation of this method.
and you can jump on that class by just click on it...

A: You can use the Assistant Editor:

*

*Open the protocol that you are interested in, place the cursor inside the @protocol definition

*Open the Assistant Edior (command-option-return) and from the drop down menu in the upper left, select Protocols:

The classes that implement the protocol will be in the list.
Edited to add info from Rob's comment:
Note that this only finds classes that, either in their public header or in their implementation declare that they conform to the protocol. If conformance to the protocol is declared somewhere else, those classes will not show up.
Say you have a protocol defined somewhere as
@protocol MyProtocol <NSObject>
…
@end

A class with a public header MyClass.h like this will show up:
@interface MyClass : NSObject <MyProtocol>

Also, a class that is extended in the .m file like this will show up
@interface MyObject () <SomeProtocol>
…
@end

@implementation MyObject
…
@end

A class extension MyClass_Extension.h like this will not show up:
@interface MyObject (Extension) <SomeProtocol>
…
@end


text:
Q: Sharing content on Facebook not displaying correctly One of the problems I have is that my title contains an "&" but it displays as "&" when I click share.
Another problem I have is that the code below does not recognize "
" or "\n".
How do I make it so it will recognize "&, ', -, etc.." as well as line breaks.
<?php
$gettitle = get_the_title();
$getcontent = get_the_content();
$content = substr($getcontent, 0, 20);
$content .= "
".$moretexthere;
$link = get_permalink();

$title=urlencode($gettitle);
$url=urlencode($link);
$summary=urlencode($content);
?>

<a onClick="window.open('http://www.facebook.com/sharer.php?s=100&p[title]=<?php echo $title;?>&p[summary]=<?php echo $summary;?>&p[url]=<?php echo $url; ?>','sharer','toolbar=0,status=0,width=548,height=325');" href="javascript: void(0)">Share

A: Well, i use this as sharer url..
https://www.facebook.com/sharer/sharer.php?u=URLENCODEDURL

A: Use the urlencode PHP function.

"This function is convenient when encoding a string to be used in a
  query part of a URL..."

http://php.net/urlencode
WordPress Example:
<?php echo urlencode(get_the_title()); ?>


text:
Q: Separate key-values in a dictionary and recreate the dict after processing the values I have a large dictionary like this:
{'T096': ['AABBAACACCAADBAACCAAAACACCBBAE'],
'T122': ['AACAABBBCABBDAACABCACABBAAACCCCAE'],
'T154': ['ABAABDBAAACCCAE'],
'T169': ['CCDBAACCAAAACCAE'],
'T176': ['BDACACCAAAACCCCAE'],
'T183': ['BBAACAACCBDAACBACCCCAAAACCAE'],
'T197': ['AABBAACABABACABAAABDBAAACCAE'],
'T178': ['CACDBAAACCCAE'],
'T067': ['BACAACCDBAABACCACCAAABCCACACCCCAE']}

I use a library that accepts a list of strings and does some processing (in this example generates common prefixes).
So I extract all values from the above dict.
Once the processing is done (in this example I get the prefixes), I am interested in assigning those processed strings (here, common prefixes) back to the keys in the dict.
E.g. something like this:
{'T096': ['AAB'],
'T197': ['AAB']}  # in the rest, there are no common prefixes, so ignored, or set to None

Now I need to be able to retain the mapping between the keys and values, even after extracting all the values. Is there a way to do that elegantly?
Edit: Replaced "get prefix" with "string processing" to reflect the broader scope of the problem!

A: Use a dictionary-comprehension with collections.Counter:
from collections import Counter

d = {'T096': ['AABBAACACCAADBAACCAAAACACCBBAE'],
'T122': ['AACAABBBCABBDAACABCACABBAAACCCCAE'],
'T154': ['ABAABDBAAACCCAE'],
'T169': ['CCDBAACCAAAACCAE'],
'T176': ['BDACACCAAAACCCCAE'],
'T183': ['BBAACAACCBDAACBACCCCAAAACCAE'],
'T197': ['AABBAACABABACABAAABDBAAACCAE'],
'T178': ['CACDBAAACCCAE'],
'T067': ['BACAACCDBAABACCACCAAABCCACACCCCAE']}

c = Counter(x[0][:3] for x in d.values())
print({k: v[0][:3] for k, v in d.items() if c[v[0][:3]] > 1})

# {'T096': 'AAB', 'T197': 'AAB'}


text:
Q: Why $\int_0^\infty \sin^2(x)/x^2 dx$ converges, and $\int_0^\infty \cos^2(x)/x^2 dx$ does not? I have the following two integrals:
$$I_1 = \int_0^\infty \frac{\sin^2(x)}{x^2}dx$$
$$I_2 = \int_0^\infty \frac{\cos^2(x)}{x^2}dx$$
I don't understand why $I_1$ converges and $I_2$ diverges. I tried $\frac{\sin^2(x)}{x^2} \le \frac{1}{x^2}$ but that does not work since $\int \frac{1}{x^2} dx$ diverges. I am convinced that one of them has to diverge since $I_1+I_2$ diverges, but I don't see why.

A: There are two problems : one in $0$ and one in $+\infty$. Both functions are integrable on an interval of the form $\left[a,+\infty\right[$ with $a>0$.
But around $0$, $\frac{\sin^2x}{x^2}\sim 1$ is integrable on $\left[0,a\right]$, but $\frac{\cos^2x}{x^2}\sim \frac{1}{x^2}$ which is not.


text:
Q: Sending data with axios in html to use in intern JS file I'm sending data from html using a button, I have the data and I want to pass it to an internal js because I don't want to expose credentials, but when I want to use it, it gives me an undefined instead of the data, that's why I need your help :c
Thanks in advance, below I show the code
My html file:

submitBtn.addEventListener("click", function (e) {

          var folder_id = location.search.slice(1).split("&")[0].split("=")[1]
          var document_id = location.search.slice(1).split("&")[1].split("=")[1]

          axios.post('/send-signature',{
            data: {
              "document_id": document_id,
              "folder_id": folder_id
            }
          })

}

My JS file
router.post("/send-signature", (req, res) => {

  const data = req.body

  console.log(data)

})

The error is that my req.body is undefined, that is, I think the data is not arriving.


text:
Q: Jackson: Deserializing String Reader is failing I am using Jakcson Databind v2.9.9. I have following code that fails.
public class Test {

    public static void main(String[] args) throws IOException {
        String test = "test";
        Reader inputString = new StringReader(test);
        ObjectMapper objectMapper = new ObjectMapper();
        Object o = objectMapper.readValue(inputString, objectMapper.constructType(SimpleType.construct(String.class)));
        System.out.println("Output: " + o);
    }
}

Exception is:
Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'test': was expecting 'null', 'true', 'false' or NaN
 at [Source: (StringReader); line: 1, column: 9]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:703)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._reportInvalidToken(ReaderBasedJsonParser.java:2853)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._reportInvalidToken(ReaderBasedJsonParser.java:2831)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._matchToken2(ReaderBasedJsonParser.java:2628)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._matchToken(ReaderBasedJsonParser.java:2606)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._matchTrue(ReaderBasedJsonParser.java:2564)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:725)
    at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4141)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4000)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3063)
    at com.feign.orch.Test.main(Test.java:16)

Any help please?


text:
Q: Microsoft Office Data Connection to utilise an external XML Data source? I want to be able to process or product for connecting an external XML data connector to Microsoft Office Products (specifically Excel) so that it's seamless to the product. Essentially the spreadsheet should act as if it's running an SQL query and update each time that you open the file.
What would be the best way for doing this?
Edit (further information):
Worth noting: Mapped XML Data sources cannot be used in pivot tables. However I would like to use the external xml data source to create pivot tables as well, if this is possible.

A: You can use Excel Get External data and specify an XML data source.  The data can be set to refresh on a variety of triggers including on file open.  Once the data is in Excel, it can be used as the source of a pivot table.
Note I have done some very basic testing done on Excel 2010 to confirm these claims. I think 2007 should work in a similar manner


text:
Q: Restore MySQL Database from another server, will it affect current databases? Morning, we have 8 databases on our live server. I have created a new one on our test/development server. In MySQL Administrator I've backed up this new database to an SQL file, this file is on the new server. If I use "restore" in MySQL Administrator to create this database, will it affect the other databases that are there or will they carry on working as normal?
Is there a better way to do this?
The new DB is only a few k in size, the others contain many years of info and data and are huge. Any help appreciated

A: No, it won't. As you said that your DB is small it will not affect at all the other DB. It would if it was bigger, most probably it would slow dow your server a bit during the import (if it was bigger, huge to be precise), after the import the database will work normally. Of course it will share resource to keep one more instance working. And with time, it will make some difference in performance (depending on how big this DB grow). But you will have to be more concerned with hardware capabilities then the database itself.
Of course, I assume that when you say database you are saying about a new instance on your database.


text:
Q: Blank screen when I use FineUI MVC Grid Control I recently download FineUI free trial package, and try to use their grid control in my new project. I made new project, I didn't have any problem when use traditional MVC framework from asp.net. But I want to use FineuiMVC grid in my project to save some development effort.
I already added Fineuimvc.dll to my project. However, I see error

After some research, I realize adding @using FineuiMvc can resolve above issue. But I still see an empty screen. The view HTML source code looks like below
  <html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grid/CheckAll - My ASP.NET Application</title>
    <!--##FineUIMvc.RenderCssExtension##-->
    <link href="/res/css/common.css" rel="stylesheet" type="text/css" />
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
    <link href="/Content/site.css" rel="stylesheet"/>
    <script src="/Scripts/modernizr-2.6.2.js"></script>
  </head>
  ....
    <!--##FineUIMvc.RenderScriptExtension##-->
    <script src="/Scripts/jquery-1.10.2.js"></script>
    <script src="/Scripts/bootstrap.js"></script>
    <script src="/Scripts/respond.js"></script>
    <script src="/res/js/grid.js"></script>
  ....
  </html>

I notice there are two placeholders in the HTML source code, but not sure the root cause. Does any one know this if you are using FineUI control?

A: *

*using FineUIMvc

To avoid write "using FineUIMvc" on every view, you need update the Views/Web.config to add FineUIMvc namespace under <system.web.webPages.razor> section. One example is
<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="FineUIMvc" />
  </namespaces>
</pages>
</system.web.webPages.razor>

*Managed pipeline mode

Please double check your project setting. If you are using Integrated mode, please change the configuration to below
<system.webServer>
<modules>
    <add name="FineUIMvcScriptModule" type="FineUIMvc.ScriptModule, FineUIMvc"/>
</modules>
<handlers>
    <add name="FineUIMvcResourceHandler" verb="GET" path="res.axd" type="FineUIMvc.ResourceHandler, FineUIMvc"/>
</handlers>
</system.webServer>

For Classic mode, it is using <system.web> tag.
BTW, http://mvc.fineui.us/ has examples for your reference.
Hope above explanation can help you out.


text:
Q: Where should I place my chromedriver file? I'm using Ubuntu 14.04. I have a Rails app "project" located at home/user/project. I want to use ChromeDriver with SeleniumWebdriver. I downloaded the ChromeDriver executable, but Selenium can't find the file. It gives me this error:
Selenium::WebDriver::Error::WebDriverError: Unable to find the chromedriver executable.
Please download the server from http://chromedriver.storage.googleapis.com/index.html and place it somewhere on your PATH

I've spent upwards of an hour reading articles/questions about PATH and environmental variables, and they keep talking about editing files like ~/.profile and ~/.bashrc and ~/.pam_environment, but from what I can tell my computer doesn't even have any of those files.
Isn't there just some folder where I can place the ChromeDriver executable so that Selenium can find it?

A: Place the file in /home/user/project and add PATH=/home/user/project:$PATH to your ~/.bashrc file. If it doesn't exist, create it.


text:
Q: How do you write down a binomial distribution of a coin toss with different yield results? I'm gambling with a $\$100$ entry fee. Heads gives me $+30\%$ gain, and tails gives me $-25\%$. I decide to pull out after $2$ flips, so the function should be written as something like:
$$X \sim B\left(2, \frac{1}{2} \right)$$
Except that the successes/fails don't quite give the same opposite results. How do I write this binomial function with $X$ as the value of my wallet after $2$ flips? Is this even a binomial distribution?

A: It's the number of heads that's binomially distributed according to $N\sim B\left(2,\frac12\right)$. The number of your dollars at the end of the experiment is $X=100\cdot 1.3^N0.75^{2-N}$.


text:
Q: git automatically ignore commits by file I'm using the following command for git to ignore commits listed in .git-blame-ignore-revs

git config blame.ignoreRevsFile .git-blame-ignore-revs

This file is tracked in a remote git repo. Every developer has to set up this command manually on first pull. I have no idea why would the file not be seen automatically like .gitignore is for example.
Is there a way to make git automatically ignore commits accroding to .git-blame-ignore-revs?


text:
Q: Creating a prototype function to destroy itself? I'm currently working with sockets.io in Node.js, I have a class called Rooms, their functions are self explanatory, its basic model looks like:
Room (owner)
this.owner = owner
occupants = []

Room.prototype = {
    sendMessage()
    getUsers()
    leaveParty()
}

But I want to make one for destroying its self, I tried doing,
Room.prototype.destroy = function() {
    this = undefined
}

and then doing
var roomVariable = new Room('blah');
roomVariable.destroy.call(roomVariable);

But that does not work, I'm running out of ideas on how to make this destroy its self, basically after there are no more users left in occupants, I want it erased from memory and all. Thanks!

A: Your Room's destroy()/dispose() method should release any resources that must be explicitly released (like an open transaction that doesn't auto-commit) and signal any known "watchers" or "subscribers" that it's closing (so they can remove their references to it). this can include your RoomContainer, or you can make your RoomContainer responsible for removing references to expired rooms. In either case, once there are no more references to the room, the garbage collector is free to remove it from memory.

A: Quick answer is: you can't.
Long answer is: destruction of a JS object and subsequent garbage collection is only possible outside of scope. You will need to hunt down and delete/unset all references of an item. This sucks, I know, but that's how it is.
Much like in PHP, this in a prototype method is actually not the object itself, merely an interface to it. You can't unset it, you can't re-define it (it'd lead to chaos and confusion otherwise).
The proper form for this is to let something else, an object manager, know that you intend to delete this. At which point, this object does the actual GC.


text:
Q: Zend Translate custom language Depending on the user role, I need to show different texts in my Zend project.

*

*For normal users I'm using the "en" language.

*For new users I want something like "en_new".

However, the language "en_new" always reverts to just "en".
I'm using the locale_directory scan system to automatically detect languages.

A: The translate adapter calls Zend_Locale::findLocale() internally in addTranslation() (at least in ZF 1.1x). This in turn checks whether the locale is on a whitelist. Yours is not, obviously. I didn't dig too deep into the code, but it's quite probable that the next step is to revert from en_xxx to just en which is what happens in your case.
See the sources:

*

*library/Zend/Translate/Adapter.php - addTranslation method

*library/Zend/Locale.php - findLocale method

A: I am currently evaluating something similar, for some users I want some texts to be differently translated. And I also ran into the problem to not be able to create a custom locale value.
Tough what I found out in my tests seems to solve/work around the problem.
See also here: Combining multiple translation sources
What I am doing is to just add a custom translation to my default ones.
$translateDef = new Zend_Translate(
   array(
       'adapter'    => 'gettext',
       'content'    => 'locale/default/',
       'locale' => 'auto',
       'scan'       => Zend_Translate::LOCALE_DIRECTORY
   )
);

$translateCust = new Zend_Translate(
   array(
       'adapter'    => 'gettext',
       'content'    => 'locale/custom/',
       'locale' => 'auto',
       'scan'       => Zend_Translate::LOCALE_DIRECTORY
   )
);

$translateDef->addTranslation(array(
       'content'    => $translateCust
    )
);

And the folder structure looks like this:
locale/
       default/
               de
               en
       custom/
               de
               en

So when doing the addTranslation it seems to overvwrites the existing ones, so for your new users, you could add custom folder with the proper translations.
For my tests this worked so far, but haven't evaluated it in depth yet.


text:
Q: Pass by Reference issue-Java During the method call compute(ee, temp1, s1, k) from method smaller() the argument value which am passing is not same as the one which am receiving, can someone help me with this issue?
*This is my problem statement-Get the least number after deleting k digits from the input number. For example, if the input number is 24635,the least number is 23 after deleting 3 digits.
I am expecting the final output to be 23 but getting infinite loop.
public class Delete3 {

    public static void main(String[] args) {
        int k = 3;
        int num = 24635;
        StringBuffer num1 =new StringBuffer(Integer.toString(num));
        int temp = 0;
        StringBuffer s = new StringBuffer(num1);
        temp = Integer.parseInt(s.deleteCharAt(0).toString());
        temp = compute(num1, temp, s, k);
        System.out.println(temp);
    }

    static int compute(StringBuffer num2, int temp, StringBuffer s, int k) {
        while (Integer.toString(temp).length() >= k) {
            for (int i = 0; i < num2.length(); i++) {
                StringBuffer s1 = new StringBuffer(num2);
                String a = s1.deleteCharAt(i).toString();
                int temp1 = Integer.parseInt(a);
                if (temp > temp1) {
                    temp = Integer.parseInt(a);
                }
            }
            StringBuffer ee = new StringBuffer(Integer.toString(temp));
            if (ee.length() >= k) {
                smaller(temp, k);
            }
        }
        return temp;
    }

    static void smaller(int temp, int k) {
        StringBuffer ee = new StringBuffer(Integer.toString(temp));
        StringBuffer s1 = new StringBuffer(ee);
        StringBuffer s2 = new StringBuffer(ee);
        Integer temp1 = Integer.parseInt(s2.deleteCharAt(0).toString());
        compute(ee, temp1, s1, k);
    }
}

A: The infinite loop you are getting is because you are calling smaller() from inside compute() and compute() from inside smaller(). If this is done intentionally then also add a terminating condition , which would prevent it from looping infinitely.

A: You can use simple code as below :
import java.util.Arrays;

public class Delete3 {

    public static void main(String[] args) {

        int num = 246235789;
        int numDigitRequired = 2;

        System.out.println(getLeastNum(num, numDigitRequired));
    }

    static int getLeastNum(int num, int numDigitRequired) {

        char[] a = (num + "").toCharArray();

        Arrays.sort(a);

        StringBuffer s = new StringBuffer();

        for (int i = 0; i < numDigitRequired; i++)
            s.append(Character.getNumericValue(a[i]));

        return Integer.parseInt(s.toString());
    }
}


text:
Q: interchangeably alter two html input form values using jquery I have two input's on a form that i'd like to be able to interchangeably alter their variable values so that if input one's variable was the current price of Bitcoins, and input two's variable was USD's: as I typed out an amount of Bitcoins in input one, it'd update the price of USD in input two, or if i typed out a price in USD in input two it would change the value of bitcoins in input one.
How would i accomplish this with jquery//javascript.

A: Here's a simple example based on a 1:800 exchange rate:
HTML
<form>
    Bitcoin
    <input type="text" id="bitcoin" value="1">

    USD
    <input type="text" id="usd" value="800">
</form>

JavaScript (requires jQuery)
$(document).ready(function() {

    $('#bitcoin').keyup(function(e) {
        var val = $(e.target).val();
        if( val == undefined ) {
            $('#usd').val("");
        }
        else {
            $('#usd').val(val * 800);
        }
    });

    $('#usd').keyup(function(e) {
        var val = $(e.target).val();
        if( val == undefined ) {
            $('#bitcoin').val("");
        }
        else {
            $('#bitcoin').val(val / 800);
        }
    });

});

Here it is on jsFiddle.


text:
Q: Expected 0 arguments, but got 1. with Redux toolkit I am currently trying to build a simple example of redux using redux/toolkit. I am not sure what I am doing wrong.
This is my store.
import { configureStore } from "@reduxjs/toolkit";
import reducer from "./workouts";

export default function () {
  return configureStore({ reducer });
}

Here is my workouts.ts file
import { createAction } from '@reduxjs/toolkit'

export interface IWorkout {
  id: number
  restTime: number
  workoutTime: number
  exercises: number[]
  numReps: number
}

export interface IState {
  workouts: IWorkout[]
}

export interface IAction {
  type: string
  payload: IWorkout[] | any
}

export const workoutAdded = createAction('workoutAdded')
export const workoutDeleted = createAction('workoutDeleted')

const defaultState: IState = {
  workouts: [],
}

let lastId = 0

const reducer = (state: IState = defaultState, action: IAction): IState => {
  switch (action.type) {
    case workoutAdded.type:
      return {
        ...state,
        workouts: [
          ...state.workouts,
          {
            id: ++lastId,
            restTime: action.payload.restTime,
            workoutTime: action.payload.workoutTime,
            exercises: action.payload.exercises,
            numReps: action.payload.numReps,
          },
        ],
      }
    case workoutDeleted.type:
      return {
        ...state,
        workouts: state.workouts.filter((workout) => workout.id !== action.payload.id),
      }
    default:
      return state
  }
}

export default reducer

And here is my index.ts file
import { render } from "react-dom";
import configureStore from "./store/store";
import { workoutAdded } from "./store/workouts";
import App from "./App";

const store = configureStore();

const newWorkout = {
  restTime: 10,
  workoutTime: 30,
  exercises: [1, 2, 3],
  NumReps: 6
};

store.dispatch(workoutAdded(newWorkout));

const rootElement = document.getElementById("root");
render(<App />, rootElement);

My error appears in index.ts file in this line:
store.dispatch(workoutAdded(newWorkout));

Not sure what I am missing. I reproduced the error in this sandbox
This is the error that I am getting in the console:

A: workoutAdded has 0 arguments, if you want to add arguments, you can implement Action
export class workoutAdded implements Action {
  readonly type = "workoutAdded"
  constructor(public payload: Workout){}
}

A: This fixed the issue. createAction can receive as a second argument a callback function that returns an object with the payload.
export const workoutAdded = createAction("workoutAdded", (workout) =>{
    return { payload: workout };
});


text:
Q: JAXB parent class tag not wanted I am converting java class into XML file using JAXB library. I dont want to create parent class tag
Example
My Main Class is ComponentDTO.java
@XmlRootElement(name = "flow")
@AllArgsConstructor
@Getter
@Setter
public class ComponentDto {
    @XmlElements({
            @XmlElement(name = "input", type = ActivityDto.class),
            @XmlElement(name = "action", type = ActivityAction.class),
            @XmlElement(name = "dropdown", type = Dropdown.class),
            @XmlElement(name = "alert", type = ActivityAlert.class),
            @XmlElement(name = "windows", type = ActivityWindow.class),
            @XmlElement(name = "script", type = Javascript.class),
    })
    List<ChildDto> dtos;

    public interface ChildDto {}

    @AllArgsConstructor
    @XmlRootElement(name = "input")
    @NoArgsConstructor
    @Getter @Setter
    public static class ActivityDto implements ChildDto {
        @XmlAttribute(name = "name")
        private String name;
    }

    @AllArgsConstructor
    @XmlRootElement(name = "action")
    @NoArgsConstructor
    @Getter @Setter
    public static class ActivityAction implements ChildDto {
        @XmlAttribute(name = "name")
        private String name;
    }

    @AllArgsConstructor
    @XmlRootElement(name = "dropdown")
    @NoArgsConstructor
    @Getter @Setter
    public static class Dropdown implements ChildDto {
        @XmlAttribute(name = "name")
        private String name;
    }

    @AllArgsConstructor
    @XmlRootElement(name = "alert")
    @NoArgsConstructor
    @Getter @Setter
    public static class ActivityAlert implements ChildDto {
        @XmlAttribute(name = "name")
        private String name;
    }

    @AllArgsConstructor
    @XmlRootElement(name = "windows")
    @NoArgsConstructor
    @Getter @Setter
    public static class ActivityWindow implements ChildDto {
        @XmlAttribute(name = "name")
        private String name;
    }

    @AllArgsConstructor
    @XmlRootElement(name = "script")
    @NoArgsConstructor
    @Getter @Setter
    public static class Javascript implements ChildDto {
        @XmlAttribute(name = "name")
        private String name;
    }
}

and when i create object for ComponentDTO and then generate xml for this class then it will generate like this
<flow>
    <dtos>
        <input name="test"/>
    </dtos>
    <dtos>
        <action name="test"/>
    </dtos>
    <dtos>
        <dropdown name="test"/>
    </dtos>
    <dtos>
        <alert name="test"/>
    </dtos>
    <dtos>
        <windows name="test"/>
    </dtos>
    <dtos>
        <script name="test"/>
    </dtos>
</flow>

but i want result like this
<flow>
    <input name="test"/>
    <action name="test"/>
    <dropdown name="test"/>
    <alert name="test"/>
    <windows name="test"/>
    <script name="test"/>
</flow>

How can i do that?


text:
Q: if else statment to display icons in react I need to display icons according to data.id value, (the example icons display is in the comment code as well. can you suggest to me how to give an else if  condition to display this icon according to the data.id value?
/* eslint-disable react/jsx-pascal-case */
import React, { Fragment, useState, useRef } from "react";
import { Col, Row } from "antd";
import { useNavigate } from "react-router-dom";
import { Menu, Transition } from "@headlessui/react";
import * as Icons from "../../assets/svg/mobile-icons";
import * as Icons2 from "../../assets/svg/icon";

import catData from  './CategoriesData'

function classNames(...classes) {
  return classes.filter(Boolean).join(" ");
}

const catWomen = catData.catWomen.map ((data) => {

  function loadIcon() {
  if (data.id === '1') {

    return <Icons2.frock01 />

  }  else if (data.id === '2') {

    return <Icons2.frock02 />

  } else if (data.id === '3'){

    return <Icons2.frock03 />

  } else if (data.id === '4'){

    return <Icons2.frock04 />

  } else if (data.id === '5'){

    return <Icons2.frock05 />

  } else  {

    return <Icons2.frock06 />
  }
}

  return(
    {
      id: data.id,
      name: data.name,
      icon: loadIcon,
      childs: data.childs
    }
  )
  }
)

const catMen = catData.catMen.map ((data) => {
  return(
    {
      id: data.id,
      name: data.name,
      icon: <Icons2.frock01 />,
      childs: data.childs
    }
  )
  }
)

const catKids = catData.catKid.map ((data) => {
  return(
    {
      id: data.id,
      name: data.name,
      icon: <Icons2.frock01 />,
      childs: data.childs
    }
  )
  }
)

/*
const catWomen = [
  { id: 1, name: "See All", icon: <Icons2.seeall />, childs: [] },
  {
    id: 2,
    name: "Clothes",
    icon: <Icons2.frock01 />,
    childs: ["item2", "item8"],
  },
  {
    id: 3,
    name: "Shoes",
    icon: <Icons2.shoes06 />,
    childs: ["item3", "item7"],
  },
  { id: 4, name: "Bags", icon: <Icons2.purse01 />, childs: ["item4", "item6"] },
  {
    id: 5,
    name: "Accessories",
    icon: <Icons2.bag05 />,
    childs: ["item5", "item2"],
  },
  { id: 6, name: "Beauty", icon: <Icons2.hat02 />, childs: ["item6", "item4"] },
];

const catMen = [
  { id: 1, name: "See All", icon: <Icons2.seeall />, childs: [] },
  {
    id: 2,
    name: "Clothes",
    icon: <Icons2.shirt1 />,
    childs: ["item2", "item8"],
  },
  { id: 3, name: "Shoes", icon: <Icons2.shoes1 />, childs: ["item3", "item7"] },
  { id: 4, name: "Bags", icon: <Icons2.bag05 />, childs: ["item4", "item6"] },
  {
    id: 5,
    name: "Accessories",
    icon: <Icons2.purse02 />,
    childs: ["item5", "item2"],
  },
  { id: 6, name: "Grooming", icon: <Icons2.hat />, childs: ["item6", "item4"] },
];

const catKids = [
  { id: 1, name: "See All", icon: <Icons2.seeall />, childs: [] },
  {
    id: 2,
    name: "Clothes",
    icon: <Icons2.shirt1 />,
    childs: ["item2", "item8"],
  },
  {
    id: 3,
    name: "Shoes",
    icon: <Icons2.shoes05 />,
    childs: ["item3", "item7"],
  },
  { id: 4, name: "Bags", icon: <Icons2.bag05 />, childs: ["item4", "item6"] },
  {
    id: 5,
    name: "Accessories",
    icon: <Icons2.bow />,
    childs: ["item5", "item2"],
  },
  {
    id: 6,
    name: "Grooming",
    icon: <Icons2.hat03 />,
    childs: ["item6", "item4"],
  },
];
*/
const Categories = () => {
  const navigate = useNavigate();

  function SubCategories(props) {
    return (
      <Transition
        enter="transition ease-out duration-100"
        enterFrom="transform opacity-0 scale-95"
        enterTo="transform opacity-100 scale-100"
        leave="transition ease-in duration-75"
        leaveFrom="transform opacity-100 scale-100"
        leaveTo="transform opacity-0 scale-95"
      >
        <Menu.Items className="origin-top absolute w-auto rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 divide-y divide-gray-100 focus:outline-none">

{props.children}

        </Menu.Items>
      </Transition>
    );
  }

  function DropDownItem(props) {
    const items = props.data.map((item) => (
      <Menu.Item key={item.id.toString()}>
        {({ active }) => (

 setChild(item.id)}
            onClick={() => {
              item.id === 1
                ? navigate(`/allproducts?mainProductCategory=${props.parent}`)
                : navigate(
                    `/allproducts?mainProductCategory=${props.parent}&category=${item.name}`
                  );
            }}
            className={classNames(
              active ? "bg-gray-100 text-gray-900" : "text-gray-700",
              "grid grid-cols-8 block px-4 py-2 text-xs"
            )}
          >

{item.name}

{item.icon}

        )}
      </Menu.Item>
    ));
    return (
      <>

{items}

      </>
    );
  }

  const [child, setChild] = useState(1);

  function LoadChilds(props) {
    const childs = props.data[props.child - 1];
    const subItems = childs.childs.map((item) => (
      <Menu.Item key={item.toString()}>
        {({ active }) => (

 navigate(`/allproducts?mainProductCategory=${props.parent}&category=${childs.name}&subCategory=${item}`)}
            className={classNames(
              active ? "bg-gray-100 text-gray-900" : "text-gray-700",
              "block px-4 py-2 text-sm"
            )}
          >
            {item}

        )}
      </Menu.Item>
    ));
    return
{subItems}
;
  }

  const dropdownRef = useRef();

  return (
    <Row className="bg-white w-full" style={{ position: "fixed", border: 0 }}>
      <Col offset={2}>

          <Menu as="div">
            <div
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
              onClick={() => navigate(`/allproducts`)}
            >

Shop

          </Menu>

          <Menu as="div">
            <Menu.Button
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >

Women

            </Menu.Button>

              <SubCategories>
                <DropDownItem data={catWomen} parent="Women" />
                <LoadChilds child={child} data={catWomen} parent="Women" />
              </SubCategories>

          </Menu>

          <Menu as="div">
            <Menu.Button
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >

Men

            </Menu.Button>

              <SubCategories>
                <DropDownItem data={catMen} parent="Men" />
                <LoadChilds child={child} data={catMen} parent="Men" />
              </SubCategories>

          </Menu>

          <Menu as="div">
            <Menu.Button
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >

Kids

            </Menu.Button>

              <SubCategories>
                <DropDownItem data={catKids} parent="Kids" />
                <LoadChilds child={child} data={catKids} parent="Kids" />
              </SubCategories>

          </Menu>

          <Menu as="div">
            <div
              className={`border-b-2 border-b-white hover:border-b-red-400 p-2`}
            >

About

          </Menu>

      </Col>
    </Row>
  );
};

export default Categories;

A: UPDATED
For the sake of your changes. You can use my function along with this. It will return an icon component for you.
return(
    {
      id: data.id,
      name: data.name,
      icon: loadIcon(data),
      childs: data.childs
    }
  )

OLD ANSWER
You can try this way
function loadIcon(data) {
   const icons = {
      ['1']: <Icons2.frock01 />,
      ['2']: <Icons2.frock02 />,
      ['3']: <Icons2.frock03 />,
      ['4']: <Icons2.frock04 />,
   }
   return icons[data.id]
}

Usage
<>{loadIcon(data)}</>

A: Well, what you can do is put your item.icon div in conditional render like below.
And use ternary operator
{data.id === '1' ?
  (

{data.icon}

  )
  :
  (
    // Anything else you want to render
  )
}


text:
Q: RuntimeError: shape '[64, 3, 32, 32]' is invalid for input of size 49152 I'm trying to train a CNN model with Cifar10 dataset and I get this error:
      8       optimizer.zero_grad()
      9       input, target = batch
---> 10       input = input.view(batch_size, n_channel, 32, 32)
     11       output = model(input)
     12       loss = loss_fn(output, target)

RuntimeError: shape '[64, 3, 32, 32]' is invalid for input of size 49152

Can someone help me? I cant solve this error.
49512=64x3x16x16 but ı dont understand where does this number come from? (I'm beginner with pytorch)
My code:
...
class CNNModel(nn.Module):
      def __init__(self) -> None:
        super().__init__()

        self.cnn1 = nn.Conv2d(3, 6, kernel_size=3, stride=1, padding=1)
        self.relu1 = nn.ReLU()

        self.maxpool1 = nn.MaxPool2d(2)

        self.cnn2 = nn.Conv2d(6, 16, kernel_size=3, stride=1,  padding=1)
        self.relu2 = nn.ReLU()

        self.maxpool2 = nn.MaxPool2d(2)

        self.fc1 = nn.Linear(8*8*16, 256)
        self.fc2 = nn.Linear(256, 10)

      def forward(self, x):
        x = self.cnn1(x)
        x = self.relu1(x)
        x = self.maxpool1(x)
        x = self.cnn2(x)
        x = self.relu2(x)
        x = self.maxpool2(x)
        x = x.view(x.size(0), -1)
        x = self.fc1(x)
        out = self.fc2(x)

        return out

    model = CNNModel()
    model

    def train_model(model, train_loader, test_loader, loss_fn, optimizer, epochs = epochs):
      for epoch in range(1, epochs + 1):
        training_loss = .0
        validation_loss = .0

        model.train()
        for batch in train_loader:
          optimizer.zero_grad()
          input, target = batch
          input = input.view(batch_size, n_channel, 32, 32)
          output = model(input)
          loss = loss_fn(output, target)
          loss.backward()
          optimizer.step()
          training_loss += loss.data

        model.eval()
        num_correct = 0
        num_examples = len(test_loader.dataset)
        for batch in test_loader:
          input, target = batch
          input = input.view(batch_size, n_channel, 32, 32)
          output = model(input)
          loss = loss_fn(output, target)
          validation_loss += loss.data
          predicted = torch.max(output.data, 1)[1]
          num_correct += (predicted == target).sum()
        accuracy = 100 * num_correct / num_examples

        print("Epoch: {}".format(epoch), "\n",
              "Training loss: {:.2f}".format(training_loss), "\n",
              "Accuracy: {:.2f}".format(accuracy), "\n",
              "Validation loss: {:.2f}".format(validation_loss)
              )

I need to write some more to get Stackoverflow to accept my question. ignore this sentence :)

A: Think view() as a rearrangement. For example, let's say we have input like
input = torch.randn(1,3,32,32)

with declaring the input we say input should have 1 batch size, 3 channels, and 32x32 width and height.
With view, we can rearrange these dimensions like
input=input.view(1,3*2*2,16,16)

So what we've seen from here is that without changing the total number (in our case this is equal to 133232 = 13221616) you can change your shape.
For the solution,
print(input.shape)

and then look at your dimension and then change accordingly with keeping in mind the total number must not be changed.


text:
Q: Iframe with variable in Wordpress? Basically every user in my Wordpress setup has inserted a spotify user link in their profile.
I need to show their followers with a follow button in the profile (front-end of course).
Spotify has this iframe to insert follow button+followers:

Now, the variable here would be the "40Ojab0UtVQFjA76qXr8Ot?si=yL4xVXNtQSau6bHS5ACU7g" that would be the artist/user ID that the users insert in their profiles (back-end).
How could achieve that automatically?
An iframe that change this variable (artist ID) for every user, taking it from a field in the user profile?
Thanks in advance

A: I understand you are able to get the string you want to change in the iframe.
<iframe src="https://open.spotify.com/follow/1/?uri=spotify:artist:".<?php echo $userId?>."&size=detail&theme=light" width="300" height="56" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowtransparency="true">

If you don't have the $userID variable with the saved value... you need to get it from your database.
$stringQuery = "here goes your query for getting the value limit 1";
$row = $wpdb -> get_results($stringQuery);
$userId -> $row -> Column;

And then show your iframe


text:
Q: Unable to get RocketChat working with SSL, what am I doing wrong? I have successfully installed RocketChat on a private server, running Ubuntu 16.04, Apache 2.4, but I can't get SSL to work.
Background: The example.com has existing LetsEncrypt ceritificates. example.com has a website running on it with SSL and RocketChat needs to be at https://chat.example.com. There are two Apache VirtualHosts for example.com and chat.example.com, both enabled.
Settings are as follows:
example.com.conf
<VirtualHost example.com:80>
        ServerName example.com
        ServerAlias www.example.com
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/example

        Alias /examplestaging /var/www/html/examplestaging

        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/example-error.log
        CustomLog ${APACHE_LOG_DIR}/example-access.log combined

        RewriteEngine on
        RewriteCond %{SERVER_NAME} =example.com [OR]
        RewriteCond %{SERVER_NAME} =www.example.com
        RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

example.com-le-ssl.conf
<IfModule mod_ssl.c>
    <VirtualHost example.com:443>
        ServerName example.com
        ServerAlias www.example.com
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/example

        Alias /examplestaging /var/www/html/examplestaging

        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/example-error.log
        CustomLog ${APACHE_LOG_DIR}/example-access.log combined
        Include /etc/letsencrypt/options-ssl-apache.conf
        SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    </VirtualHost>
</IfModule>

chat.example.com.conf
<VirtualHost *:443>
    ServerName chat.example.com
    ServerAdmin webmaster@localhost

    UseCanonicalName on
    SSLStrictSNIVHostCheck on

    ErrorLog /var/log/chat.example.com_error.log
    TransferLog /var/log/chat.example.com_access.log
    LogLevel info

    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem

    SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+$
    SSLHonorCipherOrder on
    SSLCompression off
    SSLOptions +StrictRequire

    <Location />
        Order allow,deny
        Allow from all
    </Location>

    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule /(.*) ws://localhost:3000/$1 [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket [NC]
    RewriteRule /(.*) http://localhost:3000/$1 [P,L]

    ProxyPassReverse / http://localhost:3000/
</VirtualHost>

<VirtualHost *:80>
    ServerName chat.example.com
    ServerAdmin webmaster@localhost
    UseCanonicalName Off

    ErrorLog /var/log/chat.example.com_error.log
    TransferLog /var/log/chat.example.com_access.log
    LogLevel info

    <Location />
        Order allow,deny
        Allow from all
    </Location>

    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule /(.*) ws://localhost:3000/$1 [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket [NC]
    RewriteRule /(.*) http://localhost:3000/$1 [P,L]

    ProxyPassReverse / http://localhost:3000/
</VirtualHost>

The instructions I went by are
https://rocket.chat/docs/installation/manual-installation/ubuntu/
https://rocket.chat/docs/installation/manual-installation/configuring-ssl-reverse-proxy/#running-behind-an-apache-ssl-reverse-proxy
https://asperti.com/en/bglug-slack-to-rocket-chat
All vhosts above are enabled. All apache proxy mods are enabled (according to instructions).
http://www.example.com:3000 works and I can login. I have changed the URL in the settings to https://chat.example.com.
The service file /lib/systemd/system/rocketchat.service is
[Unit]
Description=The Rocket.Chat server
After=network.target remote-fs.target nss-lookup.target nginx.target mongod.target
[Service]
ExecStart=/usr/local/bin/node /opt/Rocket.Chat/main.js
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=rocketchat
User=rocketchat
Environment=MONGO_URL=mongodb://localhost:27017/rocketchat?replicaSet=rs01 MONGO_OPLOG_URL=mongodb://localhost:27017/local?replicaSet=rs01 ROOT_URL=https://chat.example.com PORT=3000
[Install]
WantedBy=multi-user.target

Whenever I make any changes, I restart rocketchat and apache2 services.
When entering https://chat.example.com or http://chat.example.com, it instantly throws a server unavailable error, so it would seem that the reverse proxy isn't working (?). I do not have any errors in the log files for example.com-error.log, nor chat.example.com_error.log, nor error.log.
chat.example.com_error.log does include this info
[Tue Aug 13 21:25:47.062881 2019] [ssl:info] [pid 22553] AH01914: Configuring server chat.example.com:443 for SSL protocol
[Tue Aug 13 21:25:47.063611 2019] [ssl:info] [pid 22553] AH02568: Certificate and private key chat.example.com:443:0 configured from /etc/letsencrypt/live/example.com/cert.pem and /etc/letsencrypt/live/example.com/privkey.pem

What could be wrong with this setup?

A: *

*Install Caddy on the server

*Redirect the URLs to https://your RocketChat URL

*Everything will be fine.

A: Did you try to generate via certbot?
sudo certbot --apache -d example.com -d chat.example.com


text:
Q: Error: YouTubeService has leaked IntentReceiver ... Are you missing a call to unregisterReceiver()? I uses YoutubeServie API to play youtube video in my Android application. However when I exit my activity, I found the below crash log showing, even my App still works.
02-28 15:54:02.081 20374-20374/? E/ActivityThread: Service com.google.android.youtube.api.service.YouTubeService has leaked IntentReceiver com.google.android.libraries.youtube.player.audiofocus.HeadsetPlugReceiver@a843e7c that was originally registered here. Are you missing a call to unregisterReceiver()?
                                                   android.app.IntentReceiverLeaked: Service com.google.android.youtube.api.service.YouTubeService has leaked IntentReceiver com.google.android.libraries.youtube.player.audiofocus.HeadsetPlugReceiver@a843e7c that was originally registered here. Are you missing a call to unregisterReceiver()?
                                                       at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:898)
                                                       at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:699)
                                                       at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1637)
                                                       at android.app.ContextImpl.registerReceiver(ContextImpl.java:1617)
                                                       at android.app.ContextImpl.registerReceiver(ContextImpl.java:1611)
                                                       at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:488)
                                                       at com.google.android.libraries.youtube.player.service.PlaybackService.<init>(PlaybackService.java:5034)
                                                       at com.google.android.libraries.youtube.player.PlayerInjector$12.create(PlayerInjector.java:1602)
                                                       at com.google.android.libraries.youtube.common.util.Lazy.get(Lazy.java:136)
                                                       at com.google.android.libraries.youtube.player.PlayerInjector.getPlaybackService(PlayerInjector.java:575)
                                                       at com.google.android.apps.youtube.api.ApiPlayer.moveToForeground(ApiPlayer.java:493)
                                                       at com.google.android.apps.youtube.api.ApiPlayer.<init>(ApiPlayer.java:150)
                                                       at com.google.android.apps.youtube.api.service.jar.ApiPlayerService.<init>(ApiPlayerService.java:131)
                                                       at com.google.android.apps.youtube.api.service.jar.ApiPlayerFactoryService$1.run(ApiPlayerFactoryService.java:86)
                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                       at android.os.Looper.loop(Looper.java:135)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-28 15:54:02.088 20374-20374/? E/ActivityThread: Service com.google.android.youtube.api.service.YouTubeService has leaked IntentReceiver com.google.android.libraries.youtube.player.audiofocus.AudioBecomingNoisyReceiver@379c216f that was originally registered here. Are you missing a call to unregisterReceiver()?
                                                   android.app.IntentReceiverLeaked: Service com.google.android.youtube.api.service.YouTubeService has leaked IntentReceiver com.google.android.libraries.youtube.player.audiofocus.AudioBecomingNoisyReceiver@379c216f that was originally registered here. Are you missing a call to unregisterReceiver()?
                                                       at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:898)
                                                       at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:699)
                                                       at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1637)
                                                       at android.app.ContextImpl.registerReceiver(ContextImpl.java:1617)
                                                       at android.app.ContextImpl.registerReceiver(ContextImpl.java:1611)
                                                       at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:488)
                                                       at com.google.android.libraries.youtube.player.service.PlaybackService.<init>(PlaybackService.java:4043)
                                                       at com.google.android.libraries.youtube.player.PlayerInjector$12.create(PlayerInjector.java:1602)
                                                       at com.google.android.libraries.youtube.common.util.Lazy.get(Lazy.java:136)
                                                       at com.google.android.libraries.youtube.player.PlayerInjector.getPlaybackService(PlayerInjector.java:575)
                                                       at com.google.android.apps.youtube.api.ApiPlayer.moveToForeground(ApiPlayer.java:493)
                                                       at com.google.android.apps.youtube.api.ApiPlayer.<init>(ApiPlayer.java:150)
                                                       at com.google.android.apps.youtube.api.service.jar.ApiPlayerService.<init>(ApiPlayerService.java:131)
                                                       at com.google.android.apps.youtube.api.service.jar.ApiPlayerFactoryService$1.run(ApiPlayerFactoryService.java:86)
                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                       at android.os.Looper.loop(Looper.java:135)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

None of the code are from mine app, but all are in the library. I didn't register any receiver in my code, so can't unregister anything in my fragment that works with the youtubeservice.
I think the issue is similar to https://groups.google.com/forum/#!topic/android-developers/6gzpwkaRgoE but no answer given. Any idea how to get rid of this internal crash of youtube.api.service?

A: Even if you do not manually register any receiver, an activity may register it to use it in some way on the current activity. I think you should need to call unregisterReceiver() method on onPause().
Please be aware that onDestroy() and onStop() are not guaranteed to be called.
If onPause() will be called, then the Activity is no longer in the foreground.

OnStop():
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
  Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.
For more information, here's the link: http://developer.android.com/reference/android/app/Activity.html#onStop%28%29

Fortunately, I also found some stackoverflow items that you can refer to:

*

*Activity has leaked IntentReceiver that was originally registered here. Are you missing a call to unregisterReceiver()?

*Unable to play youtube video in my android app

*Are you missing a call to unregisterReceiver() ? in android
I hope this will help.


text:
Q: asp.net HTTPHandler prevents page from loading I have an ASP:NET web project with a simple HTTPHandler which filters out requests from outside IPs.
The code itself works, but the HTTPHandler prevents my page from loading. No error. No infinite load. There's just a blank page.
If I remove the reference in the config, it loads perfectly fine. It's definitely caused by the HTTPHandler. I've also stepped through the handler and the code is definitely reached, it's just that when the handler is done, the page doesn't load like it should.
Here is the code.
public class SecurityHttpHandler : IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        string ipAddress = context.Request.UserHostAddress;
        if (!IsValidIpAddress(ipAddress))
        {
            context.Response.StatusCode = 403;
        }
    }

    private bool IsValidIpAddress(string ipAddress)
    {
        return true; //for the time being, this will always return true
    }

    public void Dispose() {  } //clean
}

The handler exists in another project (i have a reference to the assembly) and the httphandler is registered in my webprojects web.config as such:
    <handlers>
        <add name="SecurityHttpHandler" verb="*"
        path="*Default.aspx"
        type="MyProjects.CommonResources.Web.SecurityHttpHandler"
        resourceType="Unspecified" />
    </handlers>

I'm running IIS 7.5 in integrated mode. .net framework 4.0.

Let me know if I should add more code. I excluded the code from my web-project as the handler itself seems to be the cause early in the asp.net pipeline.


text:
Q: how to change Bootstrap 4 layout to remove spaces and make it responsive I am currently working on a project of making a web.But after using bootstrap I got some error in spaces in between the pictures its not also responsive in web as well as in app.
The content is divided into two category Y and C the Y is fine in its space the problem is coming from C section.The category label is also not responsive .If you can fix the error please provide me with a layout which is perfect in web and app using bootstrap.
Thanks in advance!

The Y category

                Malavian  Cichlids

            plecos

The C category

                Barbs

                Cory Cats

                Freshwater Plants

A: To make t responsive try to wrap your columns in a div with class name row.


text:
Q: React DONUT not working properly when using twice on the same page I'm using donut twice on the same page but somehow it's appearing in one div only whereas I defined it in two different Divs
Library : React-donut

            Programs

            <Donut
                chartData={[
                    { name: `${this.state.programCompleted} Completed`, data: this.state.programCompleted },
                    { name: `${this.state.programStarted} Started`, data: this.state.programStarted },
                    { name: `${this.state.programNotStarted} Not Started`, data: this.state.programNotStarted },
                ]}
                chartWidth={100}
                chartHeight={300}
                title=""
                chartThemeConfig={{
                    series: {
                        colors: ['#28B463', '#F39C12 ', '#E74C3C'],
                    },
                }}
            />

            Courses

            <Donut
                chartData={[
                    { name: `${this.state.courseCompleted} Completed`, data: this.state.courseCompleted },
                    { name: `${this.state.courseStarted} Started`, data: this.state.courseStarted },
                    { name: `${this.state.courseNotStarted} Not Started`, data: this.state.courseNotStarted },
                ]}
                chartWidth={200}
                chartHeight={300}
                title=""
                chartThemeConfig={{
                series: {
                    colors: ['#28B463', '#F39C12 ', '#E74C3C'],
                },
                }}
            />

I'm using two different divs for both the donuts but they are appearing in first div only.


text:
Q: Plotting Dynamic Data For A Graph Using Flot(JQuery) I am new in Asp.Net Web development..........
I am working on a web form application which is using asp.net c#  and MS SQL Server 2008 as database. I want to plot a graph of trends based on time filters. Most importantly, I need to perform this using jquery library flot.
I want the units of trends points on y axis and date on x axis. I want to plot 4 different trends, so there will be 4 lines for 4 different trends over graph after plotting.I want to have zooming & navigation features too for the graph.
I know to fetch the data from db using web method, but how to collect this data?....... as a list or what & then how to format this data in to javascript function & plot the graph?
Below is the code snippets:
html:

    <title></title>

    <form id="form1" runat="server">

    </form>

Code:
[WebMethod]
public static List<ChartResult> GetChartData()
    {

        List<ChartResult> LstChartResData = new List<ChartResult>();

        DataSet dsResult = new objDA().Get_ChartData();
        for (int iCount = 0; iCount < dsResult.Tables[0].Rows.Count; iCount++)
        {
            ChartResult objChartRes = new ChartResult();
            objChartRes.date = Convert.ToDateTime(dsResult.Tables[0].Rows[iCount]["date"]);
            objChartRes.load = Convert.ToDecimal(dsResult.Tables[0].Rows[iCount]["load"]);
            objChartRes.whlth = Convert.ToDecimal(dsResult.Tables[0].Rows[iCount]["whlth"]);
            objChartRes.audio = Convert.ToDecimal(dsResult.Tables[0].Rows[iCount]["audio"]);
            objChartRes.ohlth = Convert.ToDecimal(dsResult.Tables[0].Rows[iCount]["ohlth"]);

            LstChartResData.Add(objChartRes);
        }

        return LstChartResData;
    }

public class ChartResult
{
    public DateTime date { get; set; }
    public decimal load { get; set; }
    public decimal whlth { get; set; }
    public decimal audio { get; set; }
    public decimal ohlth { get; set; }
}

Now how to process the result data into sucess and use the flot library function as per referenced script flot files?
Can anybody help me to perform this?.
Thanks in advance.

*

*Regards


text:
Q: Updating a table from values in an excel file I have a set of excel files with a total of around 130,000 lines. Each line has a column with an ID and a column with a name. I need to update an existing column in one table in the database and fill each ID row with its matching name.
This only needs to be done once so I was going to just use a formula in excel to make each line a query (=CONCATENATE("UPDATE Table SET Name = '", $C1, "' WHERE ID = ", $A1)) then copy all of those queries out and run them in Sql Server Management studio. Is this an OK way to do it or will the server choke on 130,000 individual queries?
What is the proper way to do it?
Thanks!

A: Import your Excel workbook to a new table, then join that with your existing table on the ID field and build an update query from that.

A: Create an SSIS package to import the data. You can have Sql Server create the SSIS package for you by right clicking on the target database name, then select  "Task" from the pop up window, and then select import data. Follow the GUI and in the first window select "Microsoft Excel" as the data source.


text:
Q: R: bar plot with two groups both stacked with barplot(), 4 variables 14 objects I want to do this with barplot() for having the same design and as a  challange.
I took this system from Thomas as template: R: bar plot with two groups, of which one is stacked which really worked great! My data.frame is:
    'data.frame':   14 obs. of  4 variables:
 $ Lw_Eink : int  64675 52434 51500 55029 60472 54274 52915 61143 64147 60305 ...
 $ Alw_Eink: int  19208 18633 18577 21210 21557 22172 22939 23417 24131 26204 ...
 $ HH_EE   : int  72740 74214 76576 75623 73725 78426 76264 80762 83474 84640 ...
 $ HH_AEE  : int  28701 29037 29210 29751 28350 29179 26348 28215 25765 27788 ...

and my suggested script:
lw = c(as.numeric(h$Lw_Eink))
alw = c(as.numeric(h$Alw_Eink))
hh = c(as.numeric(h$HH_EE))
ahh = c(as.numeric(h$HH_AEE))

vh = cbind(rbind(lw,alw,0,0),rbind(0,0,hh,ahh))[,c(1,29,2,30,3,31,4,32,5,33,6,34,7,35,8,36,9,37,10,38,11,39,12,40,13,41,14,42,15,43,
                                                   16,44,17,45,18,46,19,47,20,48,21,49,22,50,23,51,24,52,25,53,26,54,27,55,28,56)]

barplot(vh,
        main="ø Einkommen LWS-Betriebe : ø Haushaltseinkommen CH 1998-2014",
        xlab="Jahr",
        ylab="Einkommen [CHF]",
        ylim=c(0, 100000),
        las=3,
        col=c("forestgreen","blue","orange","darkolivegreen1","cornflowerblue"),
        cex.axis = 0.9, cex.lab = 1, cex.names=0.9,
        names.arg = expression("2000","","","","2001","","","","2002","","","","2003","","","","2004","","","","2005","","","","2006",
                               "","","","2007","","","","2008","","","","2009","","","","2010","","","","2011","","","","2012","","","","2013","","","")[1:56],
        space=c(.9,.2))

grid(nx=NA,ny=10,col="darkgrey")
grid(nx=NA,ny=NULL,col="darkgrey")

legend("topleft",
       c("Landwirt. Einkommen","Ausserlandwirt. Einkommen", "HH Erwerbseinkommen", "HH Aussererwerbseinkommen"),
       fill=c("forestgreen","blue","orange","darkolivegreen1","cornflowerblue"),cex=0.7)

First Error is:
    Error in cbind(rbind(lw, alw, 0, 0), rbind(0, 0, hh, ahh))[, c(1, 29,  :
  subscript out of bounds

And second:
    Error in barplot.default(vh, main = "ø Einkommen LWS-Betriebe : ø Haushaltseinkommen CH 1998-2014",  :
  falsche Anzahl von Namen

Second means: wrong quantity of numbers...
Data h is:
Lw_Eink Alw_Eink    HH_EE   HH_AEE
2000    64675   19208   72740   28701
2001    52434   18633   74214   29037
2002    51500   18577   76576   29210
2003    55029   21210   75623   29751
2004    60472   21557   73725   28350
2005    54274   22172   78426   29179
2006    52915   22939   76264   26348
2007    61143   23417   80762   28215
2008    64147   24131   83474   25765
2009    60305   26204   84640   27788
2010    55182   26308   88324   27103
2011    59474   26737   87252   27998
2012    55965   26772   90950   29809
2013    61386   27127   91414   29206

I know it's reeaally inconvenient... but I would love to have it in the same design like the rest of my semester-work.

A: Qaswed you are right, I counted the elements of every bar (total 56), which I connected through cbind, instead of every group (total 28)! Caus one column of vh symbols one group. :D
No erasmortg, it's necessary to get the right order. I show you now how data.frame vh looks like and will see:
     [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19]
lw  64675     0 52434     0 51500     0 55029     0 60472     0 54274     0 52915     0 61143     0 64147     0 60305
alw 19208     0 18633     0 18577     0 21210     0 21557     0 22172     0 22939     0 23417     0 24131     0 26204
        0 72740     0 74214     0 76576     0 75623     0 73725     0 78426     0 76264     0 80762     0 83474     0
        0 28701     0 29037     0 29210     0 29751     0 28350     0 29179     0 26348     0 28215     0 25765     0
    [,20] [,21] [,22] [,23] [,24] [,25] [,26] [,27] [,28]
lw      0 55182     0 59474     0 55965     0 61386     0
alw     0 26308     0 26737     0 26772     0 27127     0
    84640     0 88324     0 87252     0 90950     0 91414
    27788     0 27103     0 27998     0 29809     0 29206

So [,1]+[,15] build the first bar, [,2]+[,16] the 2nd bar. --> The 4 together build the first group.
And to lable the x-axis-values, I needed again 28 objects like vh has columns... So every second just empty, like I did in the question. And yup, again like Qaswed said it's unnecessary to write the [1:28] behind the expression()
Thanks Qaswed & Erasmortg. You gave me hints that let me try diffrent variantes till it worked out.


text:
Q: Problem using the Thrift APIs I have installed Cassandra on my Ubuntu VM and built the source. I was trying to use the Thrift APIs and it seems like the libthrift-0.5.jar in my bin is not the file that I need in order to interface with the running cassandra instance.
Is there some other way to install the Thrift JARs? I found the

/cassandra/interface/thrift

folder that has the Thrift source pertaining to the interface with Cassandra. When I tried doing an ant gen-thrift-java from the command line, I get a build failed with the following message:

Execute failed: java.io.IOException:
  Cannot run program "thrift" (in
  directory
  "/home/user/cassandra/interface"):
  java.io.IOException: error=2, No such
  file or directory

Can somebody give me some ideas on what do I need to do in order to work with Thrift here?
Thanks

A: You need to install Thrift
$ cd thrift
$ ./bootstrap.sh
$ ./configure
$ make
$ sudo make install


text:
Q: Accessing keys and values from nested hashmaps in Java I have a nested hashmaps in the below format in my code. When the code is executed, this class also gets executed.
public class NestedHashMap
{
   HashMap<String, HashMap<String, HashMap<String, String>>> map1 = new HashMap<String, HashMap<String, HashMap<String, String>>>();

public void hashMapData()
{
 HashMap<String, HashMap<String, String>> map2= new HashMap<String, HashMap<String, String>>();
 HashMap<String, String> map3 = new HashMap<String, String>();

 // map3 contains key as 'Student Exam Code' and value as 'Student Name'.
    // map3.put("1352", "ABCDE");
    // map3.put("4581", "JDWEF");
    // map3.put("1587", "OWELW");
 // map2 contains key as 'Exam Centre Code' and value as map3.
    // map2.put("CENTRE092", map3);
 // map1 contains key as 'Exam Paper Code' and value as map2.
    // map1.put("ENG02", map2);

 // The data in each hashmap is stored through for loop.
}

public void getData()
{
  String strValue = map1.get("ENG02").get("CENTRE092").get("1352");
  system.out.println(strValue);
}

}

I am getting the below error when the method 'getData()' gets executed.
java.lang.NullPointerException: Cannot invoke "java.util.HashMap.get(Object)" because the return value of "java.util.HashMap.get(Object)" is null
at scripts.NestedHashMap.getData(NestedHashMap.java:159)
Could someone please help to sort this issue out?


text:
Q: Python: confused about global and local variables Noob question. I'm writing a program with recursive function calls - it's a game so I'm using recursion to allow the computer to 'think ahead' by trying moves. I'm maintaining the game state in a list, and passing this to a function which alters the game state and recursively calls itself 9 or 10 times. When I tried the first version it seemed to treat the list as a global variable. I did some tests and found that variables are always treated as local, but if you alter a list inside the function (typically I am doing something simple like board[i] = "X") it alters the global list rather than act on the local list inside the function. The little example below shows what I mean: the print output is [1,2], whereas if I do the same example but make board an integer rather than a list, the value remains 1 outside the function.
Is there a simple way around this that would make python treat the list as local just inside the function, bearing in mind it needs to do this each time the function is recursively called?
def test(board):
    board[1] = 2
    return 1

board = [1] * 2
print board

A: In Python, there are two types of objects, mutable and immutable.
Mutable objects include any user-created objects, and some built-in ones which do include list, while immutable objects are like String, int, and other primitive types.
If you pass in a mutable object into a method, the method gets a reference to that same object, so you can manipulate and mutate it as you like, this is called passing by reference. While if you pass in an immutable object, the object gets passed by assignment, which assigns a new local variable with the same value as in the parameter passed.

In your case, you are passing a list object into your method, which as we discussed above, passes it by reference, hence what you are getting inside the method is a reference to the object in the scope which the method was called from. To be able to create a local list which you can change and mutate without affecting the outer one, you have two choices:

*

*Assign the passed parameter to a new variable and change and mutate that one from there.

*Use full non-mutation assignments (like assigning the entire list not just the value at an index) which will unlink your variable from the reference.

For example:
def mutate (my_list):
    my_list.append(0)

my_list = [1, 2]
print(my_list)
mutate(my_list)
print(my_list)

will output
[1, 2]
[1, 2, 0]

while
def mutate (my_list):
    my_list = my_list + [0]

my_list = [1, 2]
print(my_list)
mutate(my_list)
print(my_list)

will output
[1, 2]
[1, 2]

A: Yes: copy the list.
board = board[:]

The way you described the behavior demonstrates that you have a misunderstanding regarding how python handles object names and namespaces. I'll try to explain.
Say we do this:
# test.py

board = [1,2,3]
def test(board):
    board = board[:]

The name "board" appears 4 times above. If we run test.py directly from commandline, then here is what we have (in order):

*

*board: the global level object name

*board: the function-local object name (as part of the function definition)

*board: the function-local object name again, but being reassigned to a new object

*board[:]: a slice- or copy- of the object referred to by the function-local object name

It is critically important to recognize that you are ONLY passing the OBJECT NAME to your function. The confusion you have stems from the idea that you are passing the object itself. However, you are NOT. One of the basic reasons for this is that python manages memory for you; if you were able to pass around memory addresses and delete actual objects like in other languages, it would be very difficult to keep track of what is stored in memory (so things can be deleted when they're not needed, for example).
When the global object name board is passed to the function, a new function-local object name is created, but it still points to the same object as the global object name. This object happens to be a list, which is mutable.
Since both the global name and the function-local name point to the same mutable object, if you CHANGE that object:
board[1] = 2

...then it doesn't matter whether the change was made via the local name, or the global name; it is the same object being changed either way.
However, when you do this inside the function:
board = board[:]

The function local object name is being reassigned. There is no change to the object it was pointing to! It simply makes the local object name point to a NEW object instead of the object it pointed to before. In this particular case, the new object it is pointing to is a copy of the old object. But we could have just as easily had it point to some other object:
board = "HELLO WORLD!"

By the way, this will all work the same for any other kind of mutable (set, list, dict) or immutable (int, float, str, tuple) object. The only difference is that since an immutable object cannot be changed, it often appears as if it is a copy of that object that is being passed to the function. But it is not; it is just a function-local name that points to the same object as the global name... the same as for a mutable object.

A: A few points to make:

*

*Python makes all variables which are not declared in the scope of a function to be globals. If you want the function to act on a global variable, you can rewrite your function to make changes to an outside declared variable; rather than directly working with the variable itself and returning it, return the value you wish to update in the global.

*The object-oriented methods amongst most languages are of the type "Pass by Reference" or "Pass by Value". There is a good discussion here on that exact subject.

Hope this helps!


text:
Q: How to get value in my label when click on tableview or button Hi, I am trying to show name and email from SQLite in a label from tableView to next view, but in my log message I only get name and label name, label email are null.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *MyIdentifier = @"MyCell";
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell==nil) {
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
                                    reuseIdentifier:MyIdentifier];
    }
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    user *worddc=[Array objectAtIndex:[indexPath row]];
    cell.textLabel.text = worddc.name;
    profileVC *pvc =[[profileVC alloc]init];

    NSLog(@"name is  %@",worddc.name);

    pvc.nameLbl.text=worddc.name;

    NSLog(@"email is  %@",worddc.email);
    NSLog(@"label name is %@",pvc.nameLbl.text);

    pvc.emailLbl.text=worddc.email;

    NSLog(@"label email is %@",pvc.emailLbl.text);

    return cell;
}

in log message:
2012-12-07 17:02:28.720 loginApp[1881:c07] CONNECTION SUCCESSFUL WITH DB
2012-12-07 17:02:36.628 loginApp[1881:c07] QUERY: select email,password from login where email ='a@a.com' and password ='a'
2012-12-07 17:02:36.664 loginApp[1881:c07] QUERY: SELECT login.Name,login.id,login.Email FROM login ORDER BY login.Name ASC, login.id ASC
2012-12-07 17:02:36.667 loginApp[1881:c07] QUERY: select last_insert_rowid()
2012-12-07 17:02:38.010 loginApp[1881:c07] id 6
2012-12-07 17:02:38.011 loginApp[1881:c07] name is  a
2012-12-07 17:02:38.011 loginApp[1881:c07] email is  (null)
2012-12-07 17:02:38.012 loginApp[1881:c07] label name is (null)
2012-12-07 17:02:38.017 loginApp[1881:c07] label email is (null)

Any help or suggestion please?

A: Are you trying to load the view controller from a nib? If so you need to call – initWithNibName:bundle: on profileVC instead of just init.

A: You should implement the profileVC calling method in - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath: because cellForRowAtIndexPath will call everytime upto number of rows in your database and  your are initializing the pvc in cellForRowAtIndexPath which in every loop the scope of pvc is out of range. so Implement this call in
profileVC *pvc =[[profileVC alloc]init];

NSLog(@"name is  %@",worddc.name);

pvc.nameLbl.text=worddc.name;

NSLog(@"email is  %@",worddc.email);
NSLog(@"label name is %@",pvc.nameLbl.text);

pvc.emailLbl.text=worddc.email;

NSLog(@"label email is %@",pvc.emailLbl.text);

A: Is worddc valid (not nil)? How about Array?

A: profileVC *pvc =[[profileVC alloc]init]; it create & allocate newly in class when you allocate  new views the all valus are null it only loads view did load and load view not load other methods