text:
Q: ivy eclipse NoClassDefFoundError: org/apache/commons/lang3/StringUtils I know this question has been solved but none of the answers solve my problem. Also I am new in this.
I do get
NoClassDefFoundError: org/apache/commons/lang3/StringUtils
I can see it resolves the dependencies but when I run the jar after compilation i get class not found.
Here is my ivy.xml file
<configurations>
        <conf name="runtime" description="Runtime"/>
</configurations>

<dependencies>
    <dependency org="org.apache.commons" name="commons-lang3" rev="3.6" conf="runtime->default"/>
    <dependency org="junit" name="junit" rev="4.12" conf="runtime->default"/>
</dependencies>

and following is my build.xml
<project name="HelloWorld-build" basedir="." default="clean-deploy" xmlns:ivy="antlib:org.apache.ivy.ant">
    <property name="src.dir" location="src" />
    <property name="build.dir" location="build" />
    <property name="dist.dir" location="dist" />

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

    <target name="init" description="resolve dependencies with ivy">
        <ivy:resolve />
        <ivy:cachepath pathid="default.classpath" conf="runtime" />
    </target>

    <target name="compile" depends="init">
        <mkdir dir="${build.dir}/classes" />
        <javac srcdir="${src.dir}" destdir="${build.dir}/classes" includeantruntime="false">
            <classpath refid="default.classpath" />
        </javac>
    </target>

    <target name="package" depends="compile">
        <mkdir dir="${dist.dir}" />
        <jar destfile="${dist.dir}/HelloWorld.jar" basedir="${build.dir}/classes">
            <manifest>
                <attribute name="Main-Class" value="mypackage.HelloWorld" />
            </manifest>
        </jar>
    </target>

    <target name="deploy" depends="package">
        <java jar="${dist.dir}/HelloWorld.jar" fork="true">
        </java>
    </target>
</project>

I got problem when I run deploy target. When I run my java application manually (not using build.xml) then it works fine.
Please help me solving this issue.
And this is java file
import org.apache.commons.lang3.StringUtils;

public class HelloWorld {
    public static void main(String[] args) {
        String message = "Hello world!";
        if (!StringUtils.isEmpty(message)) {
            System.out.println(message);
        }
    }
}

A: NoClassDefFound error is thrown as the commons-lang3 is not available in the runtime classpath. You have given it only in the javac as a classpath which means it is available only in the compile stage.
Since this is an external jar not packaged with your jar, it has to be available in the runtime claspath. But when using the jar attribute, all classpath settings are ignored by Ant.
To resolve this, you can change your deploy target as below
<target name="deploy" depends="package">
    <java classname="mypackage.HelloWorld" fork="true">
        <classpath>
            <path refid="default.classpath"/>
            <path location="${dist.dir}/HelloWorld.jar"/>
        </classpath>
    </java>
</target>


text:
Q: How to implement parent methods to activity and FragmentActivity? I am working on an android application,
and I have number of activities that extend from a custom activity.
Now I created a new FragmentActivity and I need the same functions that I have implemented in my custom activity.
How can I do that?
Edit
This is an simple example
public class BaseActivity extends Activity
{
    protected void someFunction()
    {
        Log.i("TEST","This is a test");
    }
}

public class MainActivity extends BaseActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        someFunction();
    }
}

this is my FragmentActivity:
public class MyFragmentActivity extends FragmentActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // here I want to use someFunction()..
    }
}

A: In Java you can't extend more than one class.
So I guess you should extend BaseActivity from FragmentActivity instead of Activity

redpajama_set_name: RedPajamaStackExchange


text:
Q: UISearchBar in a NavigationBar width I would like to have an UISearchbar in my NavigationBar - as I've done here:

When the SearchBar gets the Focus, I'll remove the left Button with:
self.navigationItem.leftBarButtonItems = []

And try to make the UISearchBar getting the whole width of the Screen (with a Cancel Button)
    searchBar.sizeToFit()
    searchBar.showsCancelButton = true

But my UISearchBar is too wide, it looks like in this screen:

But why is that? I want to get the following result:
User clicks into the SeachBar, I'll FadeIn a UITableView for the Results - when the User presses the Cancel Button, the UITableView fades out and I'll add the "Kategorie" left Button again.
Is this a way how to solve that - or can I not use the sizeToFit() method here?

A: Seems like you placed your searched bar as a rightBarButtonItem and that spot has a right margin. Your searchBar is trying to expand to be the full width of the screen, hence it gets to be too wide.
I used a search controller and implemented didPresentSearchController and resized it there.

A: How about setting the width of the search bar equal to the screen minus the size of the 'Cancel' button, or try to add constraints between the search bar and leading space to the navigation controller.


text:
Q: Can this Trigger be improved? I am very new to both programming and Apex. I have written one Trigger on account to update contact SLA fields whenever the SLA is updated as 'Bronze' on account. My code coverage is 100%. Please advise if this code can be improved further and optimised as I have written nested for loops.
trigger MySLA on Account (after Update) {

if(Trigger.isAfter)
{
    for(account a:Trigger.new)
    {
      for(account ao:Trigger.old)
      {
    if(a.SLA__c == 'Bronze' && ao.SLA__c != 'Bronze')
    {
    list<contact> conlist = new list<contact>();
    list<Contact> cons = [select SLA_Serial_Number__c,SLA__c,SLA_Expiration_Date__c from contact where accountid IN :Trigger.new];
    for(contact c:cons)
    {
      c.SLA__c = 'Bronze';
      c.SLA_Expiration_Date__c = a.SLAExpirationDate__c;
      c.SLA_Serial_Number__c = a.SLASerialNumber__c;
      conlist.add(c);
    }
        update conlist;
    }
      }
    }
}

}

@isTest
public class testSLAupdate {

 private static testmethod void testSLAContactUpdate()
 {
     account a = new account(name='abc', SLA__c='Gold');
     insert a;
     contact c = new contact(lastname='Smith',firstname='John',accountid=a.id);
     insert c;
     a.SLA__c = 'Bronze';
     update a;
     system.assertEquals('Bronze', c.SLA__c);
     System.assertEquals(a.SLAExpirationDate__c, c.SLA_Expiration_Date__c);
     System.assertEquals(a.SLASerialNumber__c, c.SLA_Serial_Number__c);
 }
}

A: Class can be improved a lot :
Issues :
1. Query in For loop
2. Added cyclomatic complexity
3. Bad Indentation
4. Empty check before DMLs
trigger MySLA on Account (after Update) {
    Map<Id,Account> newAccountMap = trigger.NewMap;
    Map<Id,Account> oldAccountMap = trigger.OldMap;
    Set<Id> accIds = new Set<Id>();
    for(Account a : newAccountMap.values()){
        if(a.SLA__c == 'Bronze' && oldAccountMap.get(a.Id).SLA__c != 'Bronze'){
            accIds.add(a.Id);
        }
    }
    if(!accIds.IsEmpty()){
        list<contact> conlist = new list<contact>();
        list<Contact> cons = [select AccountId, SLA_Serial_Number__c,SLA__c,SLA_Expiration_Date__c from contact where accountid IN :accIds];
        for(contact c:cons)
        {
            c.SLA__c = 'Bronze';
            c.SLA_Expiration_Date__c = newAccountMap.get(c.AccountId).SLAExpirationDate__c;
            c.SLA_Serial_Number__c = newAccountMap.get(c.AccountId).SLASerialNumber__c;
            conlist.add(c);
        }
        if(!conlist.IsEmpty()){
            update conlist;
        }
    }
}

A: Slight trim down of Amit's solution:
trigger MySLA on Account (after Update) {

    Set<Id> accountIds = new Set<Id>();
    for (Account a : Trigger.new) {
        if (a.SLA__c == 'Bronze' && a.SLA__c != Trigger.oldMap.get(a.Id).SLA__c) {
            accountIds.add(a.Id);
        }
    }

    if (!accountIds.isEmpty()) {
        List<Contact> contacts = [
                select Id, AccountId
                from Contact
                where AccountId in :accountIds
                ];
        for (Contact c : contacts) {
            Account a = Trigger.newMap.get(c.AccountId);
            c.SLA__c = a.SLA__c;
            c.SLA_Expiration_Date__c = a.SLAExpirationDate__c;
            c.SLA_Serial_Number__c = a.SLASerialNumber__c;
        }
        update contacts;
    }
}


text:
Q: Seperate records from a dictionary when a specific condition is met, and use that dictionary for replacing words in string 1st problem
I have a dictionary ready. i want to separate records based on a particular key value pair.
Example
dict = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

here I want to bifurcate records into other dictionary which has same colors
so i want the output to be something like this
dict_red_color = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

dict_yellow_color = [{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'}]
2nd problem ( Code is ready, but working with single dictionary )
import re

txt = "<I love *NAME*, it is *COLOR* in color, Its price is *PRICE*>"

dict = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

pattern = r"\*([^*]+)\*"

for d in dicts:
    print(re.sub(pattern, lambda match: d[match[1]], txt))

output is
"<I love APPLE, it is RED in color, Its price is 100>
 <I love MANGO, it is YELLOW in color, Its price is 300>"

This code takes only one text string and one dictionary into account, I want to do same thing, by first bifurcating the dict into 2 parts and then those two dict which we will make in 1st problem will be used with their respective text strings, which are :
text_for_red_color = ''' <I love *NAME*, the price is *PRICE* > '''
text_for_yellow_color = ''' <I don't love *NAME*, the price is *PRICE* > '''

2 dictionaries,
dict_red_color = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

dict_yellow_color = [{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'}]

to create the final output as,
output = ''' <I love Apple, the price is 100><I love Cherry, the price is 250><I don't love Mango, the price is 300> '''

A: for your first problem
dict_red_color = [x for x in dict if x["COLOR"] == "RED"]
dict_yellow_color = [x for x in dict if x["COLOR"] == "YELLOW"]

A: Why would you use re here? Why not use string formatting? As for filtering the text based on the color use a dict with the colors as keys and the strings as values:
inputs = [{'NAME':'APPLE','COLOR' : 'RED', 'PRICE' : '100'},{'NAME':'MANGO','COLOR' : 'YELLOW', 'PRICE' : '300'},{'NAME':'CHERRY','COLOR' : 'RED', 'PRICE' : '250'}]

outputs = {'RED': "<I love {NAME}, the price is {PRICE} >", 'YELLOW': "<I don't love {NAME}, the price is {PRICE} >"}

for d in inputs:
    print(outputs[d['COLOR']].format(**d))

Output:
<I love APPLE, the price is 100 >
<I don't love MANGO, the price is 300 >
<I love CHERRY, the price is 250 >


text:
Q: Recuperar información de un usuario de Firebase Authentication estoy usando Firebase y necesito recoger la información de los usuarios de la base de datos, para el sistema de login utilizo el servido de Firebase Authentication y claro los usuario no se guardan en Firestone, actualmente puedo obtener la información del usuario con el que estoy logeado de la siguiente manera.
var user = firebase.auth().currentUser;

Pero yo lo que necesito es obtener la informacion del usuario que quiera pasandole por ejemplo el UID del usuario que necesito su información.
Muchas gracias.


text:
Q: Is there a name/term for the number range represented by sine and cosine Is there a name/term for the number range represented by sine and cosine?
I'm not sure how to ask this so I'll ask it as the following word question

*

*-180 to +180 is to degrees as

*-π to +π is to radians as

*-1 to +1 is to _______?

Is there a word that fits in _______ above?


text:
Q: Format SQL query to Python So far I have copied and pasted from SQL to Python simple codes where I have used the following formats:
sql = ("SELECT column1, column2, column3, column4 "
       "FROM table1 "
       "LEFT OUTER JOIN table2 ON x = y "
       "LEFT OUTER JOIN table3 ON table3.z = table1.y "

However now I have started to copy into Python largest and more complicated SQL codes and I find quite difficult to use the same format as the above as columns start to contain sub-codes. I have seen some python packages that format an SQL code into python and I was wondering which one you suggest or what is the best and quiker way to overcome this situation.

A: You can use python multiline strings that start and end with three `
```This is a
a multi
   line

string```
and not worry about formatting. This is what i generally use for such purposes but ideally you should go with an ORM
For reference please check
https://www.w3schools.com/python/python_strings.asp

A: For readability, you can try this
For example:
sql = """ SELECT country, product, SUM(profit) FROM sales   left join
x on x.id=sales.k GROUP BY country, product having f > 7 and fk=9
limit 5;    """

will result in:
sql = """
    SELECT
        country,
        product,
        SUM(profit)
    FROM
        sales
        LEFT JOIN x ON
            x.id = sales.k
    GROUP BY
        country,
        product
    HAVING
        f > 7
        AND fk = 9
    LIMIT 5; """


text:
Q: SwiftUI - How to get user's Memoji? I was wondering how I can get a user's Memoji with SwiftUI. Unfortunately, Apple's AvatarKit is private and can't be used in production apps.
So is there a way to get a Memoji sticker from the keyboard? I've tried looking at .keyboardType but it doesn't have any options for stickers/memoji.
I am basically wondering how I can get the Memoji to show up in the keyboard for a TextField in SwiftUI. I know you can do it outside of SwiftUI (by setting allowsEditingTextAttributes to yes).


text:
Q: Get all tables data with Node.js and SQLite Having these tables into a db:
Athlete with fields: athlete_id, name, surname, date_of_birth, height, weight, bio, photo_id
AthletePhoto with fields: photo_id, photo, mime_type
AthleteResult with fields: athlete_id, gold, silver, bronze
Game with fields: game_id, city, year
The db model:

The code so far can only send data for one of the tables:
db.serialize(function () {
    db.all(
      'SELECT athlete_id, name, surname FROM Athlete',
      function (err, rows) {
        return res.send(rows);
      }
    );
  });

so it uses that query: SELECT athlete_id, name, surname FROM Athlete.
Is there a way to combine the tables and send all data?
I've tried to combine 2 tables, Athlete and AthletePhoto but didn't send any data:
SELECT athlete_id, name FROM Athlete UNION SELECT game_id, city, year FROM Game UNION SELECT photo_id as athlete_id, mime_type as name FROM AthletePhoto

A: Assuming that your database structure correctly represents your application needs, the query which you are trying to make will look something like this:
SELECT
a.athlete_id, a.name, a.surname, a.date_of_birth, a.bio, a.height, a.weight,
ap.photo, ap.mime_type,
ar.gold, ar.silver, ar.bronze,
g.city, g.year
FROM
(
    (
        (Athlete a JOIN AthletePhoto ap ON a.photo_id = ap.photo_id)
        JOIN
        AthleteResults ar ON a.athlete_id = ar.athlete_id
    )
    JOIN
    Game g ON ar.game_id = g.game_id

)

There is one mistake in Athlete table, that date_of_birth column is defined twice. You should rename anyone of them. There is no need to use UNION in your query if you want to combine results of different tables, use JOIN instead.
JOIN Combines different tables row-wise
UNION Combines different tables column-wise


text:
Q: Making a web-client in python to authenticate to router I am trying to use python to make a web-client that will authenticate to the routers page (192.168.1.1) and once python has a successful session, do some stuff on the router.
Now the router doesn't use https. it uses http instead. The problem is that the router doesn't post the username and password plain text. It posts some hashed data and the server responds with hashed tokens. Because of this, I cannot use requests.post(url, data= query).
I do not want to use selenium and mechanize. I want to do it pythons request module. Specifically, I do not want to use libraries that manipulate browsers. I want my application to be a web-client by itself.


text:
Q: Remove a file from Perforce control without deleting from workspace? Is there a way to remove files/directories from Perforce's control without deleting the file from the client workspace?
I'm indifferent about what happens to the files/dirs in the repository, I want to ensure that they ARE NOT removed from my local workspace.
Thanks.

A: Try
p4 delete -k <file>

It will update the server, but not touch the workspace.
http://www.perforce.com/perforce/doc.current/manuals/cmdref/delete.html

A: If you're not connected to a server that supports the -k switch on the delete command, you can create a new workspace that has a different root, delete the files from there, then switch back to your original workspace.  Because the new workspace has a different root, the files in your original workspace won't be touched.

A: You can shelve the files and then delete the "shelved files" in perforce, your local files should be intact.


text:
Q: jquery preload images ok, so i have this "slideshow.html" containing just a bunch of pictures, and the "index.html".
index.html
click

slideshow.html

and i have my script like this;
$(document).ready(function(){
            $('a').click(function(){
            $('ul').append('

');
                   $('ul').load('slideshow.html',function(){
                           $('#preloader').remove();
                   });
            });
});

so i want on click to append the preloader.gif and to call the load method and after the images form the slideshow.html are loaded to remove the animation. Using my script it won;t do the thing, the page is loaded but the animation is dropped before the image is completely loaded :( thanks

A: $(document).ready(function(){
    //anchor click
$('a').click(function(){
    //empty the div
    $('div').empty();
            //perform ajax request
    $('div').load('toLoad.html',function(){
                  //hides all loaded images
        $('div.imageHolder img').hide();
                  //applies preloader for each image loaded
        $('div.imageHolder img').each(function(){
            //creates new image object
            var img = new Image();
                            //the current image src is stored in sursa variable
            var sursa = $(this).attr('src');
                            //the current image parent is stored in parent var
            var parent = $(this).parent();
                            //the load animation is appended to current image parent
            parent.append('');
           //loading image css settings
            $('img[alt="loader"]').css({'display':'block','margin':'10px auto'});
                           //this is the key
            $(img).load(function(){
                            //after image is loaded
                parent.append($(this));
                $(this).hide().fadeIn(500).css({'width':'200px','height':'80px'});
                $(this).siblings().remove();
            }).attr('src',sursa);

        });

    });
    return false;
});
   });

A: Preloading images is done differently than this. In jQuery it can be done something like this (untested):
$('

').appendTo('body');
var $img = $(new Image()).attr('src', '1.jpg').appendTo('ul li#image1');
$img.load(function() {
    $('#throbber1').hide();
});


text:
Q: NSTimer events do no occur when screen locked on iOS 5 I've seen this come up a few times but I haven't really seen a definite answer...
Since iOS 5 my application seems to run into the problem that if the user locks the screen my NSTimer stops firing after about 20 seconds in the lock screen. This makes my app which plays a sound every time the timer fires pointless if the user locks the screen.
This has only happened since I updated my device to iOS 5.
My question is that 1. Is there any workaround to having this same functionality work on updated devices or 2. What is the recommended approach to not receiving bad reviews if your app doesn't run while locked.

A: When the user locks the screen, the app enters the 'inactive' state. This is similar to but not identical toputting your app into the background. Apple's documentation states "The app is running in the foreground but is currently not receiving events. (It may be executing other code though.)"
However, after entering the inactive state the iPhone does go completely to sleep, unless something is running to keep it active... waiting for an NSTimer to fire does not satisfy this criteria, apparently. There is discussion in this previous question. One solution, it would appear, is to play your sound when your timer fires, and in the interim, play a silent sound continuously in order to prevent the iPhone from sleeping. A hack, but at least in this case not a completely ugly hack since using a sound in order to keep the iPhone awake in order to play a sound has a kind of symmetry.
Previously linked content:
From Apple's guidelines regarding implementing long-running background tasks:

Playing Background Audio
  An app that plays audio continuously (even while the app is running in the background) can register as a
  background audio app by including the UIBackgroundModes key (with the
  value audio) in its Info.plist file. Apps that include this key must
  play audible content to the user while in the background.

Are you implementing this in your app? If not, that's your issue.
Regarding #2: You could update the description of the app to indicate it does not work with the screen locked, but better would be just to make it so that it works as the user would expect. :)

A: In iOS5, Apple has introduced more background task modes, including "audio", "location", "voip", "newsstand-content", "external-accessory" and "bluetooth-central". I think you can determine which mode you can use in your app. The link is http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW24


text:
Q: Twitter bootstrap modal not showing correct image I'm having trouble with displaying the modal for the specific image clicked on to view.
If i use a link with a class it will show all of the images in that album in seperate modals (have to close them all down). I want to show the appropriate modal for the image that I click "view" on so that it is corresponding.
If i set this to id and create an id in the top div it will display the first image in the album only, no matter what image i click on.
How could I solve this?
     View

<button type="button" class="close" data-dismiss="modal">×</button>

Pansnap

<?php echo ''?>

 <?php echo 'Download'?>

A: One way to approach this is to store the various unique data components on each of the links and then have a generic handler which will load that data into the relevant elements of a single modal.
For instance, something along the lines of:
HTML
     View
     View

    <button type="button" class="close" data-dismiss="modal">×</button>

Pansnap

      Download

Where you could load each image's data into the data attributes via PHP.
JS
$(document).on('click.modal.image-data', '[href=#imageModal]', function () {
  $('#snap').attr('src',$(this).data('image'))
  $('#download').attr('href', $(this).data('download'))
})

This will load the appropriate data in the modal elements.
JSFiddle


text:
Q: How to change cursor on mouseup? I am trying to change cursor from garb to grabbing on mouseup.
I tried to add CSS class on mouseup and it is working fine but it is a little problem with this solution.
Componenet file

CSS
.cursorGrabbing{
    cursor:grabbing;
}

But the cursor is changing only after I release the mouse button.
It should change curosr immediately when i click and hold the mouse button.
Do you have any idea hot to fix this?

A: You can use (mousedown)event and(mouseup) on same element: It Will register the event when the mouse is clicked down, not needing to wait for the click to release. So, your code will be

Hope it will work for you...

A: Use both (mousedown) and (mouseup) event, and you using the wrong ngClass syntax convention, it should be:

A working stackbliz example for you


text:
Q: Can I use 7.5VDC @ 1.0A on 6V @ 2.0A device? Just what the title asks....

*

*Can I use 7.5VDC @ 1.0A on 6V @ 2.0A device?

Anyone know the answer?

A: Watts = volts X amps. One supplies 7.5 watts the other 12 watts.
Reinforcing the previous answer: No.

A: No. The supply would not be able to provide enough current and would likely overheat.

A: Looking at this from a voltage rather than power standpoint the answer is either "No" or "Maybe, but you shouldn't".
It depends on what kind of power converter is in the device you are trying to power and whether it has a hard limit of 6V or supports a voltage range.  The current is only relevant to how "well" your device deals with not getting enough power.
If your device only takes 6-6.5V then using a 7.5V supply could well destroy the circuitry in the device and make it unusable.
If your device has a well specced power converter inside then you may be okay to use it but the device may not be getting the full amount of power necessary to, say, charge batteries at full power or even power up if it needs more current.
Working out how we'll specced the power converter in your device is is not really our job, that's your manufacturers job and they likely chose that power supply for a reason.
You may or may not damage your device, but either way you're not using the right power supply for the job.


text:
Q: Spring - wrong method called I am providing the followind defition in my spring config file:
<bean id="path" class="java.nio.file.Paths" factory-method="get">
    <constructor-arg>
        <value type="java.lang.String">${limits.path}</value>
    </constructor-arg>
</bean>

Paths.get can be either called with a String parameter or URI parameter. SPring, in the above example resolves it to URI, which is wrong... Any idea why?

A: Try with a specific index, it might have a problem since it has a varargs in the method signature.
From the oracle docs :
get(String first, String... more)

Try Something like that :
<bean id="path" class="java.nio.file.Paths" factory-method="get">
    <constructor-arg index="0"
                     type="java.lang.String"
                     value="${limits.path}" />
</bean>

If it doesn't work, try with an empty list :
<bean id="path" class="java.nio.file.Paths" factory-method="get">
    <constructor-arg index="0">
        <value type="java.lang.String">${limits.path}</value>
    </constructor-arg>
    <constructor-arg index="1">
        <list></list>
    </constructor-arg>
</bean>


text:
Q: How to load Images to Kendo grid I am uploading image to the network folder which is not inside the project. Uploading images works 100%. The challenge is to read those image back to the grid, i am struggling to read all the images to Kendo grid.
**Question : How can i read images from network folder to Kendo grid **
This is what i have tried,
Reading Folder Url from the config
 string Filelocation = System.Configuration.ConfigurationManager.AppSettings["Home.Settings"];

Model
public class SettingsModel
{
    [DataType(DataType.Upload)]
    public HttpPostedFileBase UploadImage { get; set; }
    public string ImageUrl { get; set; }
}

Uploading Controller
    [HttpPost]
    [CustomAuthorize]
    public ActionResult SaveBackgroundImage(SettingsModel model)
    {
        try
        {
            string backgroundImg = "";
            string ImageName = "";
            if (model.UploadImage != null)
            {
                backgroundImg = Path.GetFileName(model.UploadImage.FileName);
                string e = Path.GetExtension(backgroundImg);
                if (model.UploadImage != null)
                {

                    ImageName = Path.Combine(Filelocation, backgroundImg);
                    model.UploadImage.SaveAs(ImageName);
                    model.ImageUrl = Url.Content(Path.Combine(Filelocation, ImageName)); // saving the Image url,wanted to try to read url

                }
            }
            return View("BackgroundImage", model);
        }
        catch (Exception ex)
        {
            return Json(new { result = false, errormsg = "Error: " + ex.Message });
        }
    }

I got this url after saving:
  \\0.0.0.000\Main\HomeSettings\BackgroundImage\20170802_174049.jpg
View
@using (Ajax.BeginForm("SaveBackgroundImage", "BackgroundSettings", new AjaxOptions { HttpMethod = "Post" }, new { @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
 {

    Upload Image:

        @Html.TextBoxFor(m => m.UploadImage, new { type = "file", @id = "id_fileUploadImage", @class = "form-control input-sm", required = "required", @accept = ".jpg,.png,.gif" })

        <button class="btn btn-primary " id="btnSaveFile" name="submit" type="submit">Upload Image</button>

@(Html.Kendo().Grid<TTAF.Portal.Parts.Web.Models.SettingsModel>()
                            .Name("Grid")
                            .Columns(columns =>
                            {
                                columns.Bound(c => c.ImageUrl).ClientTemplate("");
                                //Error here: {"Object reference not set to an instance of an object."}
                            })
                  .Pageable(pageable => pageable
                  .Refresh(true))
                  .Scrollable()
                  .DataSource(dataSource => dataSource
                  .Ajax()
                  .PageSize(1)
                  .ServerOperation(false) //No post back
                  .Read(read => read.Action("", ""))))

  }

Script

$(document).ready(function () {
    window.addEventListener("submit", function (e) {

        var form = e.target;
        if (form.getAttribute("enctype") === "multipart/form-data") {
            if (form.dataset.ajax) {
                e.preventDefault();
                e.stopImmediatePropagation();
                var xhr = new XMLHttpRequest();
                xhr.open(form.method, form.action);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var obj = JSON.parse(xhr.responseText)
                        if (obj.result == true) {
                            var ObjResults =
                            {
                                UploadImage: obj.UploadImage
                            }
                            alert(obj.UploadImage);
                            $.ajax({
                                url: '@Url.Action("SaveBackgroundImage", "BackgroundSettings")',
                                data: ObjResults,
                                type: "Post",
                                crossDomain: true,
                                async: true,
                                cache: true,

                                success: function (data) {
                                    if (data.result == true) {
                                        alert("Image Uploaded");
                                    }
                                    else {
                                        alert("Error Occured");
                                    }
                                }
                            });
                        }
                        else {;
                        }
                    }
                };
                xhr.send(new FormData(form));
            }
        }
    }, true);
});


text:
Q: Flux v2 - How to Deploy Same Helm Chart, Multiple Times, Into Different Namespaces We are building out a small cluster for a dev team.
Ive been working through this repo: https://github.com/fluxcd/flux2-kustomize-helm-example
The infrastructure part went fine.
Now instead of apps I need to create a way for each developer, to deploy/maintain their own version of the application they are working on.
├── clusters
│   └── qa
│       ├── deploys.bak
│       ├── flux-system
│       │   ├── gotk-components.yaml
│       │   ├── gotk-sync.yaml
│       │   └── kustomization.yaml
│       └── infrastructure.yaml
├── deploys
│   ├── base
│   ├── dev1
│   ├── dev2
│   ├── dev3
│   └── staging

In deploys/base it would be great to specify a Namespace, a HelmRelease, and a Kubernetes Secret.
Then in deploys/dev1 it would be great if we could include the base but have a way of overriding the namespace everything goes into.
So you would have  namespaces app-dev1, app-dev2 etc.
This would allow us to only really have to override the ingress information, and the image tag for the app.
Thanks for any information on this.

A: You need to add a patch to your kustomization.
patches:
  - target:
      kind: HelmRelease
      name: .*-helm-release
      version: v2beta1
    patch: |-
      - op: add
        path: /spec/targetNamespace
        value: dev1
      - op: replace
        path: /metadata/namespace
        value: dev1

Add this to every env that you want.


text:
Q: Break foreach loop activity based on output of webhook activity in Azure data factory I am passing some records through foreach loop activity to webhook activity in ADF
In Webhook activity I am calling Rest API to get the status code back so I get different status codes like 202,400,500 for each record. We usually receive 500 code when the API service is down
If I,m passing 5 records to foreach loop, the first request will be sent to Webhook and we get status code 500, loop has to break when we recieve status code 500 for the first record which means rest of the 4 records should not be passed to webhook activity.
Can anyone please guide me how to achieve this?
Many thanks for your help in advance

A: Wrap your call in an IF, assign a variable for the return status code initialized to 0 (or whatever) and a second variable that identifies first row (set to True/1 whatever). Have if condition as Status Code != 500 or Row > 1. Overwrite the status code variable with return from call, increment (or whatever) the first row variable.


text:
Q: When trying to create response in post request, nothing happens My signup page works fine and inputs and checks the sql database just fine however when I want to redirect to another page or rerender the signup page, it doesn't do anything, neither the res.render or the res.redirect
checkIfUserExists(body.username, function(err, result) {
    if (result[0]['COUNT(*)'] > 0) {
      res.render('account/signup', {error: "Username already exists"})
    } else {
      insertUserTable(body.username, body.password, body.email, function(err, result) {
        insertTransactionTable(body.startingBal, result)
      })
      res.redirect('/account/login')
    }
  })

The only error I get is in the browser console, which gives an error of Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Literally everything works fine except the responses


text:
Q: Get keys and values of object I have the following object in typescript:
let parameters = { include: 'tags', limit: 20, published: true };

How can I loop through each parameter and get its key and value?
I need to do something with the key and value when value is not undefined.

A: Use Object.entries, perhaps with a for-of loop and destructuring:
for (const [key, value] of Object.entries(parameters)) {
    if (value !== undefined) {
        // ...use `key` and `value` here
    }
}

A: Use Object.keys
 Object.keys(parameters).forEach(key => {

    });


text:
Q: SQL Query - Inner join matching with multiple columns I have table which has the following Columns  ID, Client ID, Provider ID. I want to pull the records if the same Client ID and Provider ID combination exists more than once. (List both) My result should look like
Column ID  Client ID  Provider ID
   R1         C1         P1
   R2         C1         P1
   R3         C2         P2
   R4         C2         P2

Appreciate your help

A: This ought to work:
;
WITH X AS(
  SELECT
  Count(*) over (partition by [Client ID], [Provider ID]) as [Cnt],
  *
  FROM
  YourDatabase..YourTable
  )
SELECT * FROM X WHERE [Cnt] >= 2


text:
Q: Left and right to cancel or confirm slider flutter I need to use a slider which slides both to the left to cancel and right to confirm
this is the desired slider
I couldn't find a way to do it, is there any way to do it ?

A: You can achieve it by using a Slider and customizing it.
...

double _currentSliderValue = 5;

Slider customSlider() {
    return Slider(
      value: _currentSliderValue,
      min: 0,
      max: 10,
      divisions: 10,
      onChanged: (double value) {
        setState(() {
          _currentSliderValue = value;
        });
        if (_currentSliderValue == 0) // Decline
        else if (_currentSliderValue == 10) // Accept
        else // Nothing
      },
    );
  }

The UI can be achieved by including the customSlider() as a child of a Row widget as follows (didn't try it but it should be the right path):

Row declineOrAcceptSlider() {
    return Row(children: [
      Text("Decline"),
      customSlider(),
      Text("Accept")
    ], mainAxisAlignment: MainAxisAlignment.spacedEvenly);
}

A: Use Gesture Detector this
Example :
@override
  Widget build(BuildContext context) {
    String swipeDirection;

    return GestureDetector(
      onPanUpdate: (details) {
        swipeDirection = details.delta.dx < 0 ? 'left' : 'right';
      },
      onPanEnd: (details) {
        if (swipeDirection == 'left') {
          //handle swipe left event
        }
        if (swipeDirection == 'right') {
          //handle swipe right event
        }
      },
      child: //child widget
    );
  }


text:
Q: How do I Autofill a cell with string depending if it's in another list? I'm trying to create a sheet where I can type one text value in and it autofills with the closest possible match from another list of strings.
I've tried using the VLOOKUP function in VBA, with 4th argument set to TRUE to look for a partial match. I've also tried using the VLOOKUP function in excel only and not VBA. The result is half of what I want, let's say I enter "cookie" in the cell, the function returns "Cleaning Supplies" since they both start with a C. Ideally, I'd want it to return Chocolate Cookie or something similar to that.
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    Set KeyCells = Range("A:A")

If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

           Target.Value = Application.WorksheetFunction.VLookup(Target.Value, Worksheets("StorageLocations").Range("A:A"), 1, True)

End If
End Sub

The code works partially, coming back with a run-time error Method 'Range' of object_ '_Worksheet' failed. It also only comes back with the cleaning supplies comment from earlier.
Any help is appreciated.

A: Try:

*

*In Worksheet event paste

Private Sub Worksheet_Change(ByVal Target As Range)

Call fnd(Target)

End Sub

*

*In a New Module Paste

Sub fnd(rng As Range)

Application.EnableEvents = False

If rng.Column = 1 Then

    If Not Worksheets("StorageLocations").Range("A:A").Find(rng) Is Nothing Then

        rng.Value = Worksheets("StorageLocations").Range("A:A").Find(rng.Text).Value

    End If

End If

Application.EnableEvents = True

End Sub

Explanation:

*

*We need this Enable Events to change the value in Sheet, otherwise while changing the cell value it will keep firing the Change Event.

*It will always give you the First available Match in the Column

Demo:


text:
Q: user with role db_datawriter can't select form database I create new logins and user in my program like this(using sql stored procedures)
//new login
SqlCommand cmd = new SqlCommand("sp_addlogin", conn);
cmd.CommandType = CommandType.StoredProcedure;
string login = radTextBox2.Text;
string password = radTextBox3.Text;
cmd.Parameters.Add(new SqlParameter("@loginame", login));
cmd.Parameters.Add(new SqlParameter("@passwd", password));
int i = cmd.ExecuteNonQuery();
....
//new user
SqlCommand cmd = new SqlCommand("sp_adduser", conn);
cmd.CommandType = CommandType.StoredProcedure;
string username = radTextBox1.Text;
string role;
try
{
   switch (radDropDownList1.SelectedItem.Text)
   {
     case "Admin": { role = "db_owner"; break; }
     case "Guest": { role = "db_datareader"; break; }
     case "User": { role = "db_datawriter"; break; }
     default: { this.radLabelElement1.Text = "Role was not chosen!"; return; }
   }
 }
 catch (NullReferenceException) { this.radLabelElement1.Text = "Role was not chosen!"; return; };
 string login = radTextBox2.Text;
 cmd.Parameters.Add(new SqlParameter("@loginame", login));
 cmd.Parameters.Add(new SqlParameter("@name_in_db", username));
 cmd.Parameters.Add(new SqlParameter("@grpname", role));
 int result = cmd.ExecuteNonQuery();

because I want every user of database to have either all permissions in database for admin, only read permissions for guests and read/write/update/delete permission for user for all tables in database by default.
I thought if db_owner allowed to do everything in the database, then db_datawriter allowed to read/write/update/delete data in the database and db_datareader only can read data from database. But when I use login and password for user with db_datawriter role I've got an exception(when I try to view datagrid) - 'the SELECT permission was denied on the object 'Tablename',database 'Databasename',schema 'dbo'...On the other hand user with db_datareader role can see it but cant edit(so it works correct).
What's the problem?

A: If you want both read and write capabilities then they'll need both db_datawriter and db_datareader roles. db_datawriter only grants write ability because there are use cases where you would want a user to be able to write to the database but not read from it.


text:
Q: search for an integer after a particular world in shell scripting I have an input to unix shell script :
     -mem some_integer cmd1 cmd2

I want to get the integer value following the word "-mem". also i want to then remove both and append a new string using value of some_integer.
my output should be like
          cmd1 cmd2 -new_flag_some_ineteger_some_unit
i have tried sed/awk but failed
Thanks
Ruchi

A: Use $2 to pick out the second command line argument.
Use shift to discard the command line arguments after you have stored them.
Like so:
N=$2
export N
shift
shift
echo $* -${N}


text:
Q: Crop a piece of a PDF page and save it as a new PDF document using itextsharp or itext7? I need to save a rectangular area of a PDF file to a new PDF file, preferably using iTextSharp or iText7. I have managed to split the page to equal-sized pages, which works fine, but now I need to take an area with a custom size and location and have that in a separate page - once this is done, I can easily extract the page and save it as a separate pdf.
The code I have so far:
        public void manipulatePdf(string src, string dest)
    {
        PdfReader reader = new PdfReader(src);
        iTextSharp.text.Rectangle pagesize = reader.GetPageSizeWithRotation(1);
        Document document = new Document(pagesize);
        PdfWriter writer = PdfWriter.GetInstance(document,
            new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite));
        document.Open();
        PdfContentByte content = writer.DirectContent;
        PdfImportedPage page = writer.GetImportedPage(reader, 1);
        float x, y;

        x = 0;// -pagesize.Width * (0 % 4);
        y = 0;// pagesize.Height * (0 / 4 - 3);
        content.AddTemplate(page, 2, 0, 0, 2, x, y);
        document.NewPage();

        document.Close();
    }

A: Posting a solution in iText 7.
We are going to create a new document with one page which will be an exact copy of the original page we want to take an area from, but with the crop box defined. The crop box will make sure that the content is cut to the area you want. Do note that in this case the rest of the content (in the invisible area) is not gone and is still present in the internal document structures, so this solution can be applied in case you don't have any sensitive information inside of your document that you want to cut out. If you do have such sensitive information, take a look at pdfSweep add-on.
PdfDocument source = new PdfDocument(new PdfReader("C:\\source.pdf"));
PdfDocument croppedSinglePageTarget = new PdfDocument(new PdfWriter("C:\\cropped.pdf"));
Rectangle area = new Rectangle(200, 400, 200, 200);
int pageToCopy = 1;
source.copyPagesTo(pageToCopy, pageToCopy, croppedSinglePageTarget);
croppedSinglePageTarget.getPage(1).setCropBox(area);
source.close();
croppedSinglePageTarget.close();

Original document:
Cropped result (200x200):


text:
Q: Call a function with a part of a larger array I'm refactoring some code and have decided that I would like to merge a two-dimensional array into a one-dimensional, larger array. The problem is now that I have some functions which take those smaller arrays as parameter and I would prefer to keep their signatures. Is it possible to call a function with only a part of a larger array?
f1 is what I currently have and f2 is what it should look like after refactoring:
#include <array>

void func(std::array<int const, 5> const& arr, int i);

void f1() {
    static std::array<std::array<int const, 5>, 2> const arr{{{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}}};
    func(arr[0], 0);
    func(arr[1], 1);
}

void f2() {
    static std::array<int const, 10> const arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
    //TODO: call func with first and last 5 elements.
}

A: If you change your function to to take a range of elements as Peter commented, this becomes trivial. You would pass arr.begin() and arr.begin() + 5 for the first array and arr.begin() + 5, arr.end() for the second.
void func(int* b, int* e, int i);

You can also take a span just to make things cleaner. Here gsl::span is used but you can write your own if you want:
#include <gsl/span>

void func(gsl::span<int> s, int i);

static std::array<int const, 10> const arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
func( {arr.begin(), arr.begin() + 5}, 0 );
func( {arr.begin() + 5, arr.end()}, 1 );


text:
Q: How to make asignment operator overloading work for continuous assignment Today I had an interview. I was asked to write a to make assignment operator overloading.
Suppose I have an 3 objects such as
className obj1, obj2, obj3;
Now I want to assign like this
obj1 = obj2 = obj3;
How to do it?
I wrote a program below, but it is throwing error as error: no match for 'operator=' in 'ab = ab1.overload::operator=((* & ab2))'
#include <iostream>

using namespace std;
class overload{
public:
    int x, y;
    overload operator=(overload &);
    overload(){x = 1; y = 2;}
};
overload overload::operator=(overload &ov)
{
    overload o;
    o.x = ov.x;
    o.y = ov.y;
    cout << o.x << "..." << o.y << endl;
return o;
}
int main()
{
    overload ab, ab1, ab2;
    ab = ab1 = ab2;
return 0;
}

A: You're modifying a local object and returning it by value. You need to modify this object
and return a reference to it:
overload& overload::operator=(const overload& ov)
{
    this->x = ov.x;
    this->y = ov.y;
    return *this;
}

The error you get is because a temporary returned by a function cannot bind to a reference to non-const (hence the const in my example).

A: The issue is that your assignment operator take a reference to non-const and returns by value. Since the value returned from the first assignment is treated as a temporary, the compiler won't bind a reference to it, so the second assignment fails. The usual form of an overloaded assignment operator is:
T &T::operator=(T const &other)
{
    ...
    return *this;
}

A: You should make the overloaded operator return a reference. Then it should work.
overload& operator=(const overload& o) {
  //do my assignment
  return *this;
}


text:
Q: I just want to put some texts between tags using appendchild methods with Javascript This code below is a javascript code to change texts and background properties from the body tag at the same time when the browser is clicked. I've just followed rules in w3school.com, actually, I'm doing the same as the examples do, but mine won't work and I've failed to find my fault. plz, help me.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
var complementary = new Array();
var j = 0;

window.onclick = function(){

    var background_color;
    var body = document.getElementsByTagName("body")[0];
    // var color = new Array();
    var result = null;

    var number = Math.round(Math.random()*0xFFFFFF);
    for(var i = 0; i > 3; i++)
    {
        complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
        j = j + 2;
    }

    var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);

    body.style.backgroundColor = "#"+ number.toString();
    bodyntext.style.color = "#"+ clnumber.toString();

}

A: Use document.getElementsByTagName("body")[0] to achieve expected result, as getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as a NodeList object.

var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv);
var complementary = new Array();
var j = 0;

window.onclick = function(){

    var background_color;
    var body = document.getElementsByTagName("body")[0];
    // var color = new Array();
    var result = null;

    var number = Math.round(Math.random()*0xFFFFFF);
    for(var i = 0; i > 3; i++)
    {
    complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
        j = j + 2;
    }

    var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);

    body.style.backgroundColor = "#"+ number.toString();
    bodyntext.style.color = "#"+ clnumber.toString();

}

codepen - https://codepen.io/nagasai/pen/NLBXJE
Please refer this link for more details - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName

A: I just change appendChild to document.body.appendChild(helloDiv) and added ID attribute for that div:

var helloDiv = document.createElement("div");
    helloDiv.id = "myDIV";
document.body.appendChild(helloDiv);

var helloText = document.createTextNode("Click me");
helloDiv.appendChild(helloText);

var complementary = new Array();
var j = 0;

window.onclick = function(){

    var background_color;
    var body = document.getElementsByTagName("body")[0];
    var helloText = document.getElementById("myDIV");
    // var color = new Array();
    var result = null;

    var number = Math.round(Math.random()*0xFFFFFF);
    for(var i = 0; i > 3; i++)
    {
    complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
        j = j + 2;
    }

    var clnumber = (complementary[6]+complementary[1]+complementary[2]).toString(16);
    var clnumber2 = (complementary[0]+complementary[2]+complementary[6]).toString(11);

    body.style.backgroundColor = "#"+ number.toString();
    helloText.style.color = "#"+number.toString();

}

A: Here's your problem

var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);

Please note that the javascript functions that have plural names often return arrays which is the case here
document.getElementsByTagName("body") returns an array and you are trying to perform an invalid action, that is append child, to this array. You need to access an element using index and then perform this action.
so using
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv); should fix your problem.


text:
Q: XML element occurrence I am writing a schema for the following XML. I want to limit the occurrence of Element_E, Element_F and Element_G to '1' and Element_D can occur n number of times. I tried to use xs:sequence but it enforces the element order, xs:choice does not check the max occurrences of above elements.
Is it possible to validate the occurrence of each element in a group through XML Schema?
<?xml version="1.0" encoding="utf-8"?>
<Element_A>                     <!-- One time occurrence -->
  <Element_B>                   <!-- One time occurrence -->
    <Element_C>                 <!-- One time occurrence -->
      <Element_D />             <!-- n time occurrence -->
      <Element_D />
      <Element_D />
      <Element_E />             <!-- One time occurrence -->
      <Element_F />             <!-- One time occurrence -->
      <Element_G />             <!-- One time occurrence -->
    </Element_C>
  </Element_B>
</Element_A>

A: With XSD 1.0, you'll have to check such a constraint in code.
With XSD 1.1, you can use xs:assert to state count invariants:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           version="1.1"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1">

  <xs:element name="Element_A">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Element_B">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Element_C">
                <xs:complexType>
                  <xs:choice maxOccurs="unbounded">
                    <xs:element name="Element_D"/>
                    <xs:element name="Element_E"/>
                    <xs:element name="Element_F"/>
                    <xs:element name="Element_G"/>
                  </xs:choice>
                  <xs:assert test="    count(Element_E) = 1
                                   and count(Element_F) = 1
                                   and count(Element_G) = 1"/>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

A: Have you looked into maxOccurs ?
<xsd:element ref="Element_E" maxOccurs="1"/>

http://www.w3schools.com/schema/schema_complex_indicators.asp


text:
Q: php + rss: why isn't the image showing up? I'm making my own RSS feed in PHP for my website, which loads the blog my website has from a table called 'blog', it all works as it should except for one thing...no images are showing up at the articles. Here's the output piece of my code:
while($data = mysql_fetch_assoc($news))
{
    echo "<item>" . chr(10);
    echo "<title>[$data[type]] $data[name]</title>" . chr(10);
    echo "<author>Johannes Jensen</author>" . chr(10);
    echo "<link>http://www.funbyjohn.com/v2/?blog=$data[url]</link>" . chr(10);
    echo "<image>" . chr(10);

    if($data["type"] == "text")
    {
        $imageurl = "http://www.funbyjohn.com/v2/gfx/mini_me.png";
    } else
    {
        $imageurl = "http://www.funbyjohn.com/v2/media/thumb-$data[date].png";
    }

    echo "<src>$imageurl</src>" . chr(10);
    echo "<title>$data[name]</title>" . chr(10);
    echo "<link>http://www.funbyjohn.com/v2/?blog=$data[url]</link>" . chr(10);
    echo "</image>" . chr(10);

    if($data["type"] == "text")
    {
        $content = $data["content"];
    } else
    {
        $content = $data["label_info"];
    }

    echo "<description>" . strip_tags(preg_replace("/\n+/", " ", $content)) . "</description>" . chr(10);
    echo "<pubDate>" . date("D, j M Y H:i:s", $data["date"]) . " GMT</pubDate>" . chr(10);
    echo "</item>" . chr(10);
}

And here's an example of the output of an article
<item>
<title>[image] Here's a new screenshot from Go Sheep!</title>
<author>Johannes Jensen</author>
<link>http://www.funbyjohn.com/v2/?blog=heres-a-new-screenshot-from-go-sheep</link>
<image>
<src>http://www.funbyjohn.com/v2/media/thumb-1277466055.png</src>
<title>Here's a new screenshot from Go Sheep!</title>
<link>http://www.funbyjohn.com/v2/?blog=heres-a-new-screenshot-from-go-sheep</link>
</image>
<description>*article goes here*</description>
<pubDate>Fri, 25 Jun 2010 06:40:55 GMT</pubDate>
</item>

Am I doing something wrong? Please help.
And here's my RSS feed for anyone that's interested:
http://www.funbyjohn.com/v2/rss.php

A: I think you need to use <url> intead of <src>.
http://cyber.law.harvard.edu/rss/rss.html#ltimagegtSubelementOfLtchannelgt

A: CDATA - (Unparsed) Character Data
The term CDATA is used about text data that should not be parsed by the XML parser.
Characters like "<" and "&" are illegal in XML elements.
"<" will generate an error because the parser interprets it as the start of a new element.
"&" will generate an error because the parser interprets it as the start of an character entity.
Some text, like javascript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA.
Everything inside a CDATA section is ignored by the parser.
A CDATA section starts with <![CDATA[ and ends with ]]>


text:
Q: Automated adding of one tag to all the posts in a category I'm currently redesigning a site that has 700+ posts, divided into about 150 different categories. Some categories have 2 posts in them, other categories have 70.
Now for every category, I want to add a tag to all the posts in that category.
Does anybody know if there is a way to automatically add a specific tag to all the posts in a category?
Or is the only way going through all the posts individually and adding a tag to each one, one by one?
Any help much appreciated!

A: A good starting point is (as always) the Codex function reference.
There's one nice little function that can be used to add tags or categories (or whatever built-in or custom taxonomy) to a post: wp_set_object_terms();. Maybe wp_set_post_terms(); is more easy to use. Further explanation can be found when you follow the link.
There are multiple ways to do this: Bulk adding with fetching all posts (for ex. from a category) with get_posts(); (or other queries), then looping through all given post objects and adding the needed tags. You could also try to add bulk editing options to your admin UI, but in your case I'd go the easiest way and just write a nice little function that adds your tags to one category and another one to check if it was added. Then proceed to the next category. Writing some custom function that catches all your added tags (true/false) and the check afterwards wouldn't be much. Dumping this into a nice table on shutdown wouldn't hurt:
function wpse31531_add_tags()
{
    global $_dump_tag_check;

    // the following array can contain any taxonomy. But you have to name it inside wp_set_post_terms. If you need to add tags, use 'post_tag' as 3rd argument.
    $tags = array( 'YOUR TAG NAME A HERE', 'YOUR TAG NAME B HERE' );

    $args = array( 'post_type' => 'post', 'numberposts' => -1, 'post_status' => published );
    $posts = get_posts( $args );
    foreach ( $posts as $post )
    {
        $check = wp_set_post_terms( intval( $post->ID ), $tags, 'post_tag', true ); // set last value to false if you want to replace existing tags.
        $_dump_tag_check[ $post->ID ]['tags'] = $check ? explode( ", ", $tags ) : 'failed';
    }
}
add_action( 'init', 'wpse31531_add_tags' );

function wpse31531_dump_tag_check()
{
    echo '

Post ID	Tags

';
    foreach ( $GLOBALS['_dump_tag_check'] as $ID => $check )
        echo "
{$ID}	{$check['tags']}
";
    echo '

';
}
add_action( 'wpse31531_dump_tag_check', 'shutdown' );

When you read through linked codex pages, you'll see that above code won't work out of the box and is more like a rough guide. It would be highly appreciated if you can edit my answer with your working code for later readers. Thanks.


text:
Q: PyQT4 how to using def from others model This code works:
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
from forma import Ui_MainWindow

class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), self.strona)

    def strona(self):
        self.ui.webView.setUrl(QtCore.QUrl("http://plemiona.pl"))

but this
funkcje.py
from PyQt4 import QtCore, QtGui, QtWebKit
from forma import Ui_MainWindow

def strona():
        self.ui.webView.setUrl(QtCore.QUrl("http://xxxx.pl"))

import sys, time, funkcje
from PyQt4 import QtCore, QtGui, QtWebKit
from forma import Ui_MainWindow

class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), funkcje.strona)

doesn't work...
Traceback (most recent call last):
  File "C:\Python33\liczbapierwsza\TribalWarsBot\funkcje.py", line 5, in przejdz_na_strone_plemion
    QtGui.QWidget.__init__(self, parent)
NameError: global name 'self' is not defined

how to import function from funkcje.py and use in e.x run.py

A: strona needs to have access to the class instance, self. I'm not sure how you would go about passing the self parameter using Qt, but you can always write a wrapper function as part of your class that calls strona and passes the self parameter. Or import types and add types.MethodType(funkcje.strona, self, MyForm) to the class constructor(__init__). That adds funkcje.strona to the class. Note that the latter is untested by me.
EDIT: Here is what to do:
class MyForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        types.MethodType(strona, self, MyForm)
        QtCore.QObject.connect(self.ui.pushButton,QtCore.SIGNAL("clicked()"), strona)

Note: This is untested.


text:
Q: Subtracting Dates in MongoDB I want to take the difference(subtraction) between the last element of "donations" array with current Date.
I am trying following code but can't get this thing right, I have spent more like a day on this problem. Please do respond with solution.
db.users.aggregate( [ { $project: { dateDifference: { $subtract: [ new Date(), {"donations":{ $slice: -1 }} ] } } } ]);

A: $slice returns portion of array. You need $arrayElemAt to return element from array at a given index.
Something like
db.users.aggregate( [ { $project: { dateDifference: { $subtract: [ new Date(), { $arrayElemAt:["$donations",-1] } ] } } } ]);


text:
Q: How can I concatenate NSAttributedStrings? I need to search some strings and set some attributes prior to merging the strings, so having NSStrings -> Concatenate them -> Make NSAttributedString is not an option, is there any way to concatenate attributedString to another attributedString?

A: Swift 3:  Simply create a NSMutableAttributedString and append the attributed strings to them.
let mutableAttributedString = NSMutableAttributedString()

let boldAttribute = [
    NSFontAttributeName: UIFont(name: "GothamPro-Medium", size: 13)!,
    NSForegroundColorAttributeName: Constants.defaultBlackColor
]

let regularAttribute = [
    NSFontAttributeName: UIFont(name: "Gotham Pro", size: 13)!,
    NSForegroundColorAttributeName: Constants.defaultBlackColor
]

let boldAttributedString = NSAttributedString(string: "Warning: ", attributes: boldAttribute)
let regularAttributedString = NSAttributedString(string: "All tasks within this project will be deleted.  If you're sure you want to delete all tasks and this project, type DELETE to confirm.", attributes: regularAttribute)
mutableAttributedString.append(boldAttributedString)
mutableAttributedString.append(regularAttributedString)

descriptionTextView.attributedText = mutableAttributedString

swift5 upd:
    let captionAttribute = [
        NSAttributedString.Key.font: Font.captionsRegular,
        NSAttributedString.Key.foregroundColor: UIColor.appGray
    ]

A: If you're using Cocoapods, an alternative to both above answers that let you avoid mutability in your own code is to use the excellent NSAttributedString+CCLFormat category on NSAttributedStrings that lets you write something like:
NSAttributedString *first = ...;
NSAttributedString *second = ...;
NSAttributedString *combined = [NSAttributedString attributedStringWithFormat:@"%@%@", first, second];

It of course it just uses NSMutableAttributedString under the covers.
It also has the extra advantage of being a fully fledged formatting function — so it can do a lot more than appending strings together.

A: Try this:
NSMutableAttributedString* result = [astring1 mutableCopy];
[result appendAttributedString:astring2];

Where astring1 and astring2 are NSAttributedStrings.

A: I'd recommend you use a single mutable attributed string a @Linuxios suggested, and here's another example of that:
NSMutableAttributedString *mutableAttString = [[NSMutableAttributedString alloc] init];

NSString *plainString = // ...
NSDictionary *attributes = // ... a dictionary with your attributes.
NSAttributedString *newAttString = [[NSAttributedString alloc] initWithString:plainString attributes:attributes];

[mutableAttString appendAttributedString:newAttString];

However, just for the sake of getting all the options out there, you could also create a single mutable attributed string, made from a formatted NSString containing the input strings already put together. You could then use addAttributes: range: to add the attributes after the fact to the ranges containing the input strings. I recommend the former way though.

A: 2020 | SWIFT 5.1:
You're able to add 2 NSMutableAttributedString by the following way:
let concatenated = NSAttrStr1.append(NSAttrStr2)

Another way works with NSMutableAttributedString and NSAttributedString both:
[NSAttrStr1, NSAttrStr2].joinWith(separator: "")

Another way is....
var full = NSAttrStr1 + NSAttrStr2 + NSAttrStr3

and:
var full = NSMutableAttributedString(string: "hello ")
// NSAttrStr1 == 1

full += NSAttrStr1 // "hello 1"
full += " world"   // "hello 1 world"

You can do this with the following extension:
// works with NSAttributedString and NSMutableAttributedString!
public extension NSAttributedString {
    static func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString {
        let leftCopy = NSMutableAttributedString(attributedString: left)
        leftCopy.append(right)
        return leftCopy
    }

    static func + (left: NSAttributedString, right: String) -> NSAttributedString {
        let leftCopy = NSMutableAttributedString(attributedString: left)
        let rightAttr = NSMutableAttributedString(string: right)
        leftCopy.append(rightAttr)
        return leftCopy
    }

    static func + (left: String, right: NSAttributedString) -> NSAttributedString {
        let leftAttr = NSMutableAttributedString(string: left)
        leftAttr.append(right)
        return leftAttr
    }
}

public extension NSMutableAttributedString {
    static func += (left: NSMutableAttributedString, right: String) -> NSMutableAttributedString {
        let rightAttr = NSMutableAttributedString(string: right)
        left.append(rightAttr)
        return left
    }

    static func += (left: NSMutableAttributedString, right: NSAttributedString) -> NSMutableAttributedString {
        left.append(right)
        return left
    }
}

A: If you're using Swift, you can just overload the + operator so that you can concatenate them in the same way you concatenate normal strings:
// concatenate attributed strings
func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString
{
    let result = NSMutableAttributedString()
    result.append(left)
    result.append(right)
    return result
}

Now you can concatenate them just by adding them:
let helloworld = NSAttributedString(string: "Hello ") + NSAttributedString(string: "World")

A: // Immutable approach
// class method

+ (NSAttributedString *)stringByAppendingString:(NSAttributedString *)append toString:(NSAttributedString *)string {
  NSMutableAttributedString *result = [string mutableCopy];
  [result appendAttributedString:append];
  NSAttributedString *copy = [result copy];
  return copy;
}

//Instance method
- (NSAttributedString *)stringByAppendingString:(NSAttributedString *)append {
  NSMutableAttributedString *result = [self mutableCopy];
  [result appendAttributedString:append];
  NSAttributedString *copy = [result copy];
  return copy;
}

A: You can try SwiftyFormat
It uses following syntax
let format = "#{{user}} mentioned you in a comment. #{{comment}}"
let message = NSAttributedString(format: format,
                                 attributes: commonAttributes,
                                 mapping: ["user": attributedName, "comment": attributedComment])

A: private var fillAttributes:[NSMutableAttributedString.Key : Any]? = nil

fontAttributes = [.foregroundColor : SKColor.red,
                  .strokeWidth : 0.0,
                  .font : CPFont(name: "Verdana-Bold",
                  .size : 50,]

fontAttributes.updateValue(SKColor.green, forKey: .foregroundColor)


text:
Q: Smart query syntax for singe values in PL/SQL I've been trying to find an alternative to the for (<query>) loop <statements> end loop; syntax in PL/SQL for single values. The reason is purely one of code maintainability and readability point of view, ie I want to get rid of the declaration as the for (<query>) loop <statements> end loop; does.
You can do the following:
declare
   id myTable.id%type:= 4;
   result myTable%rowtype;
begin
   select mt.* into result
     from myTable mt
     where mt.id = id;

   <do something with result>
end;

But I believe the below way is cleaner and would like something similar for single values with exceptions being thrown on NO_DATA_FOUND and TOO_MANY_ROWS as usual with select into:
for result in (select * from myTable mt where mt.id = id) loop
  <do something with result>
end loop;

Just to repeat myself, the important part is maintainability, so getting rid on having to declare a a variable which might only be used in a short scope is vital. If closures or other forms of scoping is needed does not matter, performance does not matter (up to a factor of roughly 1000), code readability and maintainability does.
What I am wondering is if you know a way which is better or cleaner in your taste than either the for loop with extra check for possible no data (TOO_MANY_ROWS is usually avoided with constraints so that check can be avoided) or the select into statement which requires a declared variable?


text:
Q: QOpenGLShaderProgram: is possible to make error output nice? I'm implementing some numerical algorithms on GPU via OpenGL and Qt.
But i am not very familiar with it.
I want to extract some functions from my current shader to some "shader library" and use it in my other shaders by string interpolation. It not hard to implement but i don't know how handle shader's compile errors
I use following code to compile shader
QOpenGLShaderProgram *shaderProgram = new QOpenGLShaderProgram();
if (!shaderProgram->addShaderFromSourceFile(QOpenGLShader::Fragment,fragmentShaderFileName)) {
    qDebug() << "Failed to compile fragment shader";
    //..........

When some compile error appears Qt print following message (an example)
QOpenGLShader::compile(Fragment): 0:331(9): error: syntax error, unexpected NEW_IDENTIFIER, expecting ',' or ';'

*** Problematic Fragment shader source code ***
//my shader source code

Is possible to catch error line number and use it to build my own error message? (with highlighted line)

A: According to the Qt documentation, you can use QOpenGLShaderProgram::log():

Returns the errors and warnings that occurred during the last link()
  or addShader() with explicitly specified source code.

You can then parse the resulting string to build your own error message.


text:
Q: Overriding yellow autofill background After a long struggle, I've finally found the only way to clear autofill styling in every browser:
$('input').each(function() {
    var $this = $(this);

    $this.after($this.clone()).remove();
});

However, I can't just run this in the window load event; autofill applies sometime after that. Right now I'm using a 100ms delay as a workaround:
// Kill autofill styles
$(window).on({
    load: function() {
        setTimeout(function() {
            $('.text').each(function() {
                var $this = $(this);

                $this.after($this.clone()).remove();
            });
        }, 100);
    }
});

and that seems safe on even the slowest of systems, but it's really not elegant. Is there some kind of reliable event or check I can make to see if the autofill is complete, or a cross-browser way to fully override its styles?

A: There's a bug open over at http://code.google.com/p/chromium/issues/detail?id=46543#c22 relating to this, it looks like it might (should) eventually be possible to just write over the default styling with an !important selector, which would be the most elegant solution. The code would be something like:
input {
    background-color: #FFF !important;
}

For now though the bug is still open and it seems like your hackish solution is the only solution for Chrome, however a) the solution for Chrome doesn't need setTimeout and b) it seems like Firefox might respect the !important flag or some sort of CSS selector with high priority as described in Override browser form-filling and input highlighting with HTML/CSS. Does this help?

A: If you're using Chrome or Safari, you can use the input:-webkit-autofill CSS selector to get the autofilled fields.
Example detection code:
setInterval(function() {
    var autofilled = document.querySelectorAll('input:-webkit-autofill');
    // do something with the elements...
}, 500);

A: I propose you avoiding the autofill in first place, instead of trying to trick the browser
<form autocomplete="off">

More information: http://www.whatwg.org/specs/web-forms/current-work/#the-autocomplete
If you want to keep the autofill behaviour but change the styling, maybe you can do something like this (jQuery):
$(document).ready(function() {
  $("input[type='text']").css('background-color', 'white');
});

A: $(window).load(function()
{
    if ($('input:-webkit-autofill'))
    {
        $('input:-webkit-autofill').each(function()
        {
            $(this).replaceWith($(this).clone(true,true));
        });
        // RE-INITIALIZE VARIABLES HERE IF YOU SET JQUERY OBJECT'S TO VAR FOR FASTER PROCESSING
    }
});

I noticed that the jQuery solution you posted does not copy attached events. The method I have posted works for jQuery 1.5+ and should be the preferred solution as it retains the attached events for each object. If you have a solution to loop through all initialized variables and re-initialize them then a full 100% working jQuery solution would be available, otherwise you have to re-initialize set variables as needed.
for example you do: var foo = $('#foo');
then you would have to call: foo=$('#foo');
because the original element was removed and a clone now exists in its place.


text:
Q: Pandas not recognizing numeric value and ljust at the same time I am new to Python and ran into bit of a stand-still with my process.
What it does: Reads in a CSV file, does some rearranging, outputs new file with re-arranged columns and values.
The problem: My output CSV has to be in a specific format so it can be consumed properly.. this included quotes around all values (including the header) and having padded values (with spaces).
I am using PANDAS to do all computations
The important logic is here:
 df['QUANTITY1'] = df['QUANTITY1'].astype(str).apply(lambda x: x.ljust(7)).astype(object)
 df['QUANTITY2'] = df['QUANTITY2'].astype(str).apply(lambda x: x.ljust(7)).astype(object)

These quantity values are float numbers, so in order to apply the space padding (ljust), I have to convert it to a string.
When I go to output the csv and write it, I am using something like this:
df.to_csv(writeFileTo, sep=',', encoding='utf-8', index=False, quoting=csv.QUOTE_NONNUMERIC, columns=['STATUS'.ljust(20),'TIME'.ljust(25), 'QUANTITY1', 'QUANTITY1'])

The output works great, but the problem is the QUANTITY1 and QUANTITY2 columns contain output with quotes (i think this is becuase csv.QUOTE_NONNUMERIC views that column as string, not numeric).
So... I decide to change the two columns back to floats so that it won't have quotes in the output. Problem number 2: when i change the values to float, they don't preserve the spacing (ljust). What do I do to keep the spacing but also have pandas not output quotes?!
TLDR; I need to have ljust or rjust float numbers in pandas csv output


text:
Q: TypeORM transaction with query builder I have some question with TypeORM transaction.
So my code is like below:
  public createOrderTransaction = async (
    data: CreateOrderInputDTO,
  ): Promise<Order> => {
    const queryRunner = this.connection.createQueryRunner();
    await queryRunner.startTransaction();
    try {
      const order = await this.createOrder(data);
      await this.createOrderRecord(order.id, data);
      await queryRunner.commitTransaction();
      return order;
    } catch (error) {
      this.logger.error(
        "Transaction Error: 'createOrderTransaction' is failed: ",
        error,
      );
      if (queryRunner.isTransactionActive) {
        await queryRunner.rollbackTransaction();
      }
    }
  };

And one function like createOrder use query builder:
private createOrder = async (data: CreateOrderInputDTO): Promise<Order> => {
    const { identifiers } = await this.orderRepository
      .createQueryBuilder('order')
      .insert()
      .into(Order)
      .values([data])
      .execute();

    await this.saveOrderDetail(identifiers[0].id, data.orderDetails);

    await this.orderRepository
      .createQueryBuilder('order')
      .relation(Order, 'orderDetails')
      .of(identifiers[0].id)
      .add(data.orderDetails);

    return this.getOrder(identifiers[0].id);
  };

But when I try it, and if it fire some error middle of logic, rollback doesn't work.
The way I see it, It seem that query builder doesn't support transaction.
So Is there any way to use quert builder with transaction?

A: Self Answer...
After I am looking into TypeORM index.d.ts, I take it that there are some parameter in createQueryBuilder named queryRunner so. If you input there your own query runner for transaction you can use queryBuilder with queryRunner
As like:
  public createOrderTransaction = async (
    data: CreateOrderInputDTO,
  ): Promise<Order> => {
    const queryRunner = this.connection.createQueryRunner();

    await queryRunner.connect();
    await queryRunner.startTransaction();
    try {
      const order = await this.createOrder(data, queryRunner);
      await this.createOrderRecord(order.id, data, queryRunner);
      await queryRunner.commitTransaction();
      return order;
    } catch (error) {
      this.logger.error(
        "Transaction Error: 'createOrderTransaction' is failed: ",
        error,
      );
      if (queryRunner.isTransactionActive) {
        await queryRunner.rollbackTransaction();
      }
    }
  };

createOrder as like:
 private createOrderRecord = async (
    orderId: string,
    data: CreateOrderInputDTO,
    queryRunner?: QueryRunner,
  ): Promise<void> => {
    await this.orderRecordRepository
      .createQueryBuilder('order_record', queryRunner)
      .insert()
      .into(OrderRecord)
      .values([
        {
          ...data,
          orderId,
          createdAt: new Date(),
        },
      ])
      .execute();

    await this.orderRecordRepository
      .createQueryBuilder('order_record', queryRunner)
      .relation(OrderRecord, 'orderDetails')
      .of(orderId)
      .add(data.orderDetails);
  };


text:
Q: Accessing c:var variable inside sql:param I am facing problem in accessing the jsp "core tag" in jsp "sql tag" for a query.
Code :
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

<sql:setDataSource
    var="myDS"
    driver="org.postgresql.Driver"
    url="jdbc:postgresql://localhost:xxxx/xyz"
    user="xyz" password="test123"
/>
<% String user_Email = session.getAttribute("email").toString();
   out.println("Email = "+ user_Email); %>
  <c:set var="emailid" value= "${user_Email}"/>

<sql:query var="listUsers"   dataSource="${myDS}">

    SELECT * FROM developer_apikey_registration where email_id = ?  ;
    <sql:param value="${emailid}"/>

</sql:query>

I am not able to get the email value here. Although I checked that it is coming correctly in the session attribute.
Please help me in this regard. I am new to JSP
Thanks in Advance.

A: Try this code
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<sql:setDataSource
    var="myDS"
    driver="org.postgresql.Driver"
    url="jdbc:postgresql://localhost:xxxx/xyz"
    user="xyz" password="test123"
/>
  <c:set var="emailid" value= "${sessionScope[user_Email]}"/>
<sql:query var="listUsers"   dataSource="${myDS}">
    SELECT * FROM developer_apikey_registration where email_id = ?  ;
    <sql:param value="${emailid}"/>
</sql:query>

Hope this helps !!

A:     <%String pkgName=null;%>
    <%String apiKey=null;%>
    <% String user_Email = session.getAttribute("email").toString();
       String email = null;
     if(session.isNew())
        {
             RequestDispatcher rdp=request.getRequestDispatcher("index.jsp");
             rdp.forward(request, response);
        }
    %>
   <%= user_Email %> // To check if email is not null

List of users

            Email
            Package Name
            API Key
             Operation

  <%
       try
       {
         Connection con=DbConn.getConnect();
         Statement st=con.createStatement();
         String q1="select * from  developer_apikey_registration where email_id ='"+user_Email+"'";
         ResultSet rs1=st.executeQuery(q1);

         while(rs1.next())
                {

                   email = rs1.getString("email_id");
                   pkgName = rs1.getString("package_name");
                   apiKey = rs1.getString("apikey");
                   %>

                <%=email%>
                <%=pkgName%>
                <%=apiKey%>
                <input type ="button" name="editBtn" id ="edtBtn" value="Edit">
        <input type ="button" name="deleteBtn" id ="delBtn" value="Delete">

    <%
                }

       }
       catch(Exception e)
               {
                e.printStackTrace();
           }

    %>


text:
Q: async function on route.js file | nodejs I have an application that it has nodejs as backend and some scripts in Python
The problem is to make the 'PythonShell' (function to access the scripts) as a async function. I do not know why but it is not working.
I'll put the code from my router.js file and inside of it I put three 'console.log('steps')' to check the sequences.
It should be Step01 > Step02 > Step03, but as it is not working, It always prints Step01 > Step03 > Step02
Everything is working fine, except for this async problem! For me it should work as it is.
How can I edit my functions to execute first the 'goToscript/PythonShell' and then execute 'res.json(responseScript)'?
Thanks
   router.put("/uploads/script-03", async (req, res) => {

    let options = {
        scriptPath: "scripts",
        args: JSON.stringify(req.body)
    };

    const goToScript = async () => {

        await PythonShell.run("script-01.py", options, (err, res) => {
            if (err) {
            }
            if (res) {
                responseScript = JSON.parse(res)
                console.log('Step 02')
            }
        });
    }

    console.log('Step 01')

    goToScript()

    console.log('Step 03')

    res.json(responseScript)
});

module.exports = router

A: A couple things:
1. Your goToScript is not actually async/returning a Promise
From what I can tell, PythonShell doesn't support async, only callbacks, so you can rewrite your gotToScript like so:
const goToScript = () => {
  return new Promise((resolve, reject) => {
    PythonShell.run("script-01.py", options, (err, res) => {
      if (err) {
        reject(err)
      }

      if (res) {
        responseScript = JSON.parse(res)
        console.log('Step 02')

        resolve(responseScript)
      }
    })
  })
}

const scriptResult = await goToScript()

This code will work like a regular async function, where the promise will resolve to the parsed JSON, and reject with the error if it meets one.
2. You are not awaiting your call to goToScript
When you want to make an async call that finishes in sequence with everything else, you need to await it. Take these two examples:
In this first chunk of code, waitFn waits before 100ms before logging "Step 2!":
const waitFn = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Step 2!')
      resolve()
    }, 100)
  })
}

console.log('Step 1!')
waitFn()
console.log('Step 3!')

Because you do not await the result of the Promise, your code doesn't care that is has not finished, and will print:
Step 1!
Step 3!
Step 2!

Instead, however, if you await the result of the Promise returned in waitFn, it will execute in order:
const waitFn = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Step 2!')
      resolve()
    }, 100)
  })
}

console.log('Step 1!')
await waitFn() // Finishes before moving on
console.log('Step 3!')

You can read a bunch more about Promises and async/await here :)

A: To be able to await function - this function needs to return a promise. In the npm page of your lib there is a description, about what PythonShell.run returns. It does not return a promise. So it is asynchronous, but not awaitable, it is callback based.
All you need to do - to promisify this function. Additionaly - you need to await the call to goToScript();.
router.put("/uploads/script-03", async (req, res) => {
  let options = {
    scriptPath: "scripts",
    args: JSON.stringify(req.body)
  };

  const goToScript = async () => {
    return new Promise((resolve, reject) => {
      PythonShell.run("script-01.py", options, (err, res) => {
        console.log("Step 02");
        if (err) return reject(err);
        return resolve(JSON.parse(res));
      });
    });
  };

  console.log("Step 01");
  const responseScript = await goToScript();

  console.log("Step 03");
  res.json(responseScript);
});

module.exports = router;


text:
Q: Spacemacs yellow line I am a novice when use Spacemacs. when edit c++ files. there are yellow highlight lines. so I want to disable the yellow highlight and what does the yellow hightlight means?

A: The yellow highlights are whitespace. If you do not want whitespace to show you can add (setq show-trailing-whitespace nil) to the dotspacemacs/user-config section in your .spacemacs (open with SPC f e d and reload with SPC f e R).
I prefer to keep the whitespace highlighting enabled and remove trailing whitespace automatically. This can be done by changing the variable dotspacemacs-whitespace-cleanup in dotspacemacs/init to 'all, 'trailing or 'changed.


text:
Q: Manage keyboard events through class in Qt C++ I'm trying to retrieve a key, and then pass it to the window class...
I stuck to it...
Here is my code:
#include "mainwindow.h"
#include "game.h"
#include <QApplication>
#include <QKeyEvent>
#include <QString>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Game g(4);
    MainWindow w;

    w.doSomething();

    while(QString text = keyPressEvent(QKeyEvent *e)->text()){ // this is not working
        g.action(text);
        w.update(g.getState());
    }

    w.show();

    return a.exec();
}

Should I wrap the Game class inside the w class as a private member or something?
I tried... without success.
Thanks.

A: keyPressEvent  is a QWidget member function, so if you need to listen to the key events, you should override it in your subclass.
It looks like, from the code you provided, for you it should be MainWindow.


text:
Q: FCEUX stops responding when i run this code made by me --llama a IUP

require("iuplua")

--Variables

on= 1

puntos1=memory.readbyte(0x0007DE) --Read the points value
puntos2=memory.readbyte(0x0007DF)
puntos3=memory.readbyte(0x0007E0)
puntos4=memory.readbyte(0x0007E1)
puntos5=memory.readbyte(0x0007E2)

p1=puntos1*100000 --Convert the raw values to it's game value
p2=puntos2*10000
p3=puntos3*1000
p4=puntos4*100
p5=puntos5*10

maxpuntaje=p1+p2+p3+p4+p5 --Calculate the final result

mundo=memory.readbyte(0x00075F) --Read the "world" value
nivel=memory.readbyte(0x000760) --Read the "level" value

estado=memory.readbyte(0x000770) --Read the mario "state" (00 not in game, 01 playing, 03 game over)

--Escribir las variables anteriores al morir

memory.writebyte(0x00075A,00) --Change the "lives" value to 1

while(on==1) do
estado=memory.readbyte(0x000770)
print(estado)
print(type(estado))
if(estado==03)then
    print("Puntuacion maxima (sesion actual) = ",maxpuntaje)
    print("Mundo y nivel Actual: ",mundo+1,"-",nivel+1)
end

end
(code edited)
This is the state of 0x000770 when playing
This is the state of 0x000770 when the Game Over scene jumps in
is there anything wrong? fceux just stop responding when i run this script, im new at stacks overflow and at programming so, every help will be welcome

A: It's rather simple to debug this but more information is required

*

*Make sure (estado==03) yields true and also print following variables and add into your question
mundo=memory.readbyte(0x00075F)
nivel=memory.readbyte(0x000760)
estado=memory.readbyte(0x000770)
print(mundo, nivel, estado)

*Check the types of these memory read vaiables i-g print(type(mundo))

*Make Sure that the if condition checks against correct types

*You realize that memonry is read once and while is always true

Try this:

while(on==1) do
    estado=memory.readbyte(0x000770)
    print(estado)
    print(type(estado))
    if(estado==03)then
        print("Puntuacion maxima (sesion actual) = ",maxpuntaje)
        print("Mundo y nivel Actual: ",mundo+1,"-",nivel+1)
    end
end

A: im so sorry for wasting your time, but i found the error, it was actually quite simple, there was a missing FCEU.frameadvance at the end of the cycle.
i dont know why it caused the emulator to crash but after putting it in place it stopped crashing. thanks to wsha for helping.


text:
Q: Replace Newline And Following Whitespaces Until A Specific String In A File How can I replace newline and following whitespaces until a specific string using one-liner sed or perl?
e.g. I want to replace newline and following whitespaces before a string 'XYZ' in a file. All line starting with word 'XYZ' will be appended before previous line (with one extra whitespace).

lorem ipsum dolor sit amet
  XYZ lorem ipsum dolor sit amet
    XXX lorem ipsum dolor sit amet
  DDD lorem ipsum dolor sit amet
      XYZ lorem ipsum dolor sit amet
cccc lorem ipsum dolor sit amet

   XYZ lorem ipsum dolor sit amet

the output will be

lorem ipsum dolor sit amet XYZ lorem ipsum dolor sit amet
    XXX lorem ipsum dolor sit amet
  DDD lorem ipsum dolor sit amet XYZ lorem ipsum dolor sit amet
cccc lorem ipsum dolor sit amet XYZ lorem ipsum dolor sit amet

A: perl -0777pe's/\n\s*(?=XYZ)/ /g' file

-0777 causes the entire file to be considered one line.
The command as written will output to STDOUT, which you can redirect as you please. -i~ and -i will edit "in place", with and without backup respectively.

A: Try this:
s/[\s\n]+XYZ/ XYZ/gsm;


text:
Q: Estimating energy requirement I read somewhere that a large part of BMR is explained by body weight. Using a data in hand, I used step wise regression with BMR as dependent variable and gender, age, height and weight as independent variables and obtained the following models with variables entered at each stage:
model 1: gender                   R2 = 0.772
model 2: gender, weight           R2 = 0.979
model 3: gender, weight, age      R2 = 0.985

Can somebody please interpret what the result I have obtained is?


text:
Q: cannot install bootstrap in angular Hello i am starting in angular i have this error when i want to install bootstrap in my project
npm WARN icss-utils@5.0.0 requires a peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN postcss-modules-extract-imports@3.0.0 requires a peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN postcss-modules-local-by-default@4.0.0 requires a peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN postcss-modules-scope@3.0.0 requires a peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN postcss-modules-values@4.0.0 requires a peer of postcss@^8.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.3 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/watchpack-chokidar2/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/webpack-dev-server/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ bootstrap@3.3.7
updated 1 package and audited 1491 packages in 49.489s

78 packages are looking for funding
  run `npm fund` for details

found 1 moderate severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details

I tried to make npm audit fix but it also produce an error

A: try using
ng add @ng-bootstrap/ng-bootstrap

it will take care of importing the module(NgbModule) and update your styles.scss

A: For ngx bootstrap, the steps are as follows:
1- Open your terminal and use the below command to install ngx-bootstrap on your machine:
 npm install ngx-bootstrap

2-Now, you need the bootstrap CSS file. You can get it using the CDN
Alternatively, install bootstrap within the angular.json file
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css" ],