text:
Q: Form submission with two buttons "save" and "save & submit"? I have one form with around 50 fields and two submit buttons, "SAVE" and "SAVE & SUBMIT". If the user clicks "SAVE", then insert the value up to which user have filled in the form. When user clicks "SAVE & SUBMIT" button, it should update or insert all the fields which user have filled in the form. Please help me out if any one have any solution. I am newbie.
<form id="myform">
<input type="text" name="field1" />

<input type="text" name="field2" />

<input type="text" name="field3" />

<input type="text" name="field4" />

<input type="submit" id="button1" value="Save" />
<input type="submit" id="button2" value="Submit" />
</form>

From the above form if user have entered values in field1 and field2 and then click on save the data should insert in the mysql and if user have fill all the fields then user can click on save and submit then data should update or insert in the mysql.

A: You can set value for the fields which the user have entered before. Otherwise check if there is no insertion in mysql then insert a new row while clicking save button or else update mysql on clicking save and submit button.
 <input type="text" name="field1"  value={value} />

Kindly refer these for better understanding.
https://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
http://falkencreative.com/forum/records/view.php


text:
Q: Replace all NaN value using the the value of another table How can I change null value and replace them using the value in the same row?
   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          NaN

I want to change NaN in index 2, replacing it with the value of user in index 2 and add 1 to it.
So that the NaN will become 2.0:
   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          2.0

A: Looks like you want fillna:
df['days_unseen'] = df['days_unseen'].fillna(df['user'].add(1))

Or, with boolean indexing:
df.loc[df['days_unseen'].isna(), 'days_unseen'] = df['user'].add(1)

output:
   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          2.0

A: I would suggest the following code:
import numpy as np
import pandas as pd
df = pd.DataFrame({'user': [1.0, 4.0, 1.0],'days_unseen': [2.0, 5.0, np.NaN]})
df.loc[df['days_unseen'].isna(), 'days_unseen'] = df.loc[df['days_unseen'].isna(), 'user'] + 1.0

A: you were very close to a solution. Here is mine:
import pandas as pd

df = pd.read_csv('sample.csv')
print(f"Initial df:\n{df}")
df["days_unseen"] = df["days_unseen"].fillna(df["user"] + 1)
print(f"\nFinal df:\n{df}")

Output:
Initial df:
   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          NaN

Final df:
   user  days_unseen
0   1.0          2.0
1   4.0          5.0
2   1.0          2.0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Broken SQL Query I have a database query that works perfect;
SELECT
    campaigns.cid, campaigns.aid, campaigns.weburl, CampCount
FROM
    campaigns
LEFT JOIN
    (SELECT
         adtracking.cid, count(*) AS CampCount
     FROM adtracking
     WHERE adtracking.createdate = [todays date]
     GROUP BY adtracking.cid ) AS adtracking ON campaigns.cid = adtracking.cid
WHERE
    campaigns.catid = '1'
    AND campaigns.campaigncomplete = '0'
    AND campaigns.active = '1'
    AND (adtracking.cid IS NULL OR CampCount < campaigns.dailynumberofimpressions)
ORDER BY
    RAND()
LIMIT 1

1st the advertises table is a one to many of the campaigns. So it;s on advertiser to many campaigns. aid is te advertiser id and that is the link to the campaign table. cid is the campaign id.
A new field was just put into the advertiseter table called adminstop and it can have values of "0" for false and "1" for true. If this claue is true than ALL of the campaigns for this aid will no longer run.
So i was attempting to put into the query
where campaign.cid in (select cid from advertisers where aid.adminstop = '0')

I am having no luck whatsoever. Any help would be appreciated.
Thanks,
jeff Goldstein


text:
Q: MOSFET Constant Current Source
Can someone explain to me how to set the IREF current with just RSET?
One end of the resistor has VDD which is fixed but how do I know what the other end (gate/drain of Q1) will be??

A: If Vdd >> Vgsth, then the variation of Id with Vgsth will be fairly small.
If Vgsth is not well controlled, or Vdd is very low, then this circuit is too simple to deliver a settable, or even constant, current.

A: Take, for example, the 2N7000 MOSFET and look at figure 1 in the data sheet: -

Because the drain is connected to the gate, \$V_{DS} = V_{GS}\$ hence we can draw a line on the above graph like so: -

So, given that current into the gate is zero (DC), you can estimate  \$V_{GS}\$ (aka \$V_{DS}\$) based on the current into \$R_{SET}\$. This then means you can calculate \$R_{SET}\$ based on \$V_{DD}\$.
So, if you were looking for a drain current of 250 mA, \$V_{DS}\$ would be about 3.6 volts. If \$V_{DD}\$ is 10 volts then, \$R_{SET}\$ equals (10 - 3.6)/0.25 = 25.6 Ω typically.
But, remember there will be considerable variation if you bench tested several devices from different batches of MOSFET.


text:
Q: How should standards and process improvements be introduced to an organization without them? I've been tasked with improving the software development process through the implementation of process improvements, of which we will most likely be using CMMI for Development, Version 1.3 as a guideline and adopting the best practices in whole or in part. What is the best way to introduce standards and process improvements so that the degree of push back and resistance from developers is minimized?

A: A couple thoughts from the school of hard knocks:
1) Most process improvement initiatives spend 80% of their time on process design and 20% on education and socialization.  Flip these percentages.  A mediocre standard that's followed beats a perfect one that isn't.
2) Identify clear reasons why you're asking people to change how they work.  What's the business case?  Ideally it benefits every team individually.  Sometimes it's just systemic improvement.  Either way, make the case visible.
3) Simplify, then standardize, not the other way around.
4) You can't fully delegate this to a PMO.  Direct managers need to be bought in, and the head of the business unit will need to break ties when complaints come in.
5) Find friendly early adopters.  People will complain about how much time it all takes.  You need someone you can point to and say, "it only took them 15 minutes"
6) For metrics, push hard for quantitative over qualitative.  Otherwise you have projects that are Green until a day before Go Live, when everything slips by a month.
7) Emphasize techniques over tools.  Good planning is more important than MS Project.
8) Put in a level of process relative to the needs.  Every restaurant needs process, but Nobu and the French Laundry need a different kind than McDonalds.  Same with software firms.
Good luck!

A: Basing your efforts on the CMMI is probably a good idea, even if you don't undergo the appraisals and get formally audited and rated. There's plenty of literature available about the CMMI, CMMI and other process improvement techniques such as Lean and Six Sigma, and CMMI and agile software development. The SEI has an entire collection of resources, some available for free, about different aspects of CMMI and guidance for different types of organizations.
I'd recommend looking in great depth at the continuous approach to implementing CMMI, rather than the staged approach. It strikes me as a much more efficient way to determine exactly where your organization stands now and improve in areas that add the most business value. This will allow you to not only align your improvement efforts with business objectives, but quickly achieve progress milestones and demonstrate the effects of improvement, increasing buy-in from all levels.
Something to keep in mind, though, is that process improvement is generally more successful when it's a grassroots effort. When process changes are dictated from above - by people the developers "in the trenches" might see as being out of touch with how things are done in the trenches - there is probably going to be pushback, even if the idea is a good one. Be prepared for this.
Some type of engineering process group might also be beneficial. Bring together representatives of the various organizational components and teams impacted by the improvement so that everyone's voice is heard. This would include not just representatives of each role, but perhaps various product development teams. Without knowing how your organization is structured, I can't say exactly who you might want to look at, but include people from every level of the organization in the group. Also, make the discussions and decisions made by this group available to the organization for comments and raising of any problems.

A: *

*Start software process improvement (SPI) project. Define its scope and goals. It will definitely help if standardization has its own goals and measure applicable to your organization.

*Assign person responsible for adopting standards. It also might be several people or even department in the case of large organization. Important thing is that all those responsible for the standardization would be:

*

*professional enough to see the whole picture

*influential enough in order to deal with teams and help them to adopt/negotiate changes

*Develop trainings covering both standard you want to adopt and its specifics applied to your organization. And its really important as long as all people who were not trained are potentially resistant to changes. For example, when I worked in a large company, I instructed all newcomer employees about QA processes, CMMI, ISO and Quality Management System. Such training was obligatory. It helped to improve knowledge about the quality management processes and raise employees awareness regarding the important issue of software quality.

*Negotiate changes and tailor generally accepted practices for your specific needs. It will help to avoid bureaucracy and implementation of heavy-weight processes nobody really need.

*Establish monitoring of how implemented process improvements are being supported and whether they are effective enough in your organization.

It will also help if you will find all the people within your organization who are truly concerned about the quality. Most probably, those would be the most important resource helping you to promote changes and establish mature practices.

A: For each change:

*

*Call out the 1 change and how it will improve development.

*Implement the change.

*Demonstrate improvement

*Remove changes that did not demonstrate improvement
Obviously the analysis needs to happen over time, but no change should be accepted until it's demonstrated to be effective.  That's also why I would implement no more than 2-3 changes per cycle otherwise you often can't measure if there has been improvement or not.
Nothing irritates me more than blindly following best practices without doing the analysis to show that is actually is a best practice for your environment.  A best practice that doesn't demonstrate improvement is at best wasteful and at worst damaging.
All steps in your process and all practices in methodology should analyzed and proved to be of benefit.  If it isn't it should be removed.  This analysis should be done on an on-going basis regardless of adding or removing steps or practices.


text:
Q: messaging between native web components v1 I have two native web components in a nested setup like below
<top-nav theme="aqua">
  <nav-link selected>Dashboard</nav-link>
  <nav-link>Settings</nav-link>
  <nav-link>Profile</nav-link>
  <nav-link>Logout</nav-link>
</fancy-tabs>

The rendering works fine for each component individually but now I need to add communication between them.
Simplest use-case is to set a link to be selected.
By default dashboard is selected link.
Now when I click settings link, settings link becomes selected, but how do I tell the dashboard component to remove the selected attribute because only one link can be active at any moment.
I am thinking to fire an event from clicked element, catch the event in top-nav element, then loop through all children and remove selected attrib if the element is not the origin of the event.
But this looks very Jquery era approach and something is not right about that.
Any other ideas?

A: One solution is :

*

*save a reference to the currently selected element

*to listen to click events at the <top-nav> container level,

*when you catch an event event, inspect its target to get the clicked <nav-link> child,

*refresh the old and new <nav-link> elements.

selected = tn.querySelector('nav-link[selected]')
tn.addEventListener('click', ev => {
  if (selected != ev.target) {
    selected.removeAttribute('selected')
    selected = ev.target
    selected.setAttribute('selected', '')
  }
})
nav-link { cursor: pointer }
nav-link[selected] { background-color: yellow }
<top-nav id="tn" theme="aqua">
  <nav-link selected>Dashboard</nav-link>
  <nav-link>Settings</nav-link>
  <nav-link>Profile</nav-link>
  <nav-link>Logout</nav-link>
</top-nav>


text:
Q: Windows 10 Проводник. Сортировка папок и файлов вместе Есть 2 файла и одна папка
Файлы:
"1"
"3"

Папка:
"2"

И их сортировка в результате даёт
"1"
"3"
"2"

или
"2"
"1"
"3"

Как заставить именно дефолтный Проводник сортировать как надо?
5 лет назад не компьютере с Win7 всё сортировалось нормально.


text:
Q: Git remove duplicate commits from history So.... I say trying to remove a file from history as it contained a password (I know - should have been in gitignore from the start!).  I followed https://help.github.com/articles/remove-sensitive-data/ to point 6 but I had an issue with my SSH key being used by Git Bash (usually use sourcetree as store the repository on BitBucket) that had to be fixed and now I have a duplicate of all commits in my history (except the latest two).
The duplicate commits are independent when looking at the parents.  In effect it looks as though there are two branches of master that have never merged.
Here is a look at the top and bottom of my log:
Top and bottom of log
If anyone can suggest how I can clean this up I would greatly appreciate it.

A: Not a sourcetree user but you clean up your history with rebase.
git rebase -i HEAD~x

Where x is the # of commits you want to go back by.
If you want to just visually clean up your history and keep the commits you can use the squash option. If you want to remove the commits altogether you can just remove the commits by deleting the lines in your editor.

A: If the number of commit is not so much, then creating a new branch and using git cherry-pick get commit you need one-by-one can be a solutions perhaps. Of cause you can write script to do it. After finished it, you can delete old branch you do not want.
By the way.

I thought squash would squash a commit with its parent

This is not correct, git rebase -i provide several options, not only squashing a commit with its parent.

A: After a comment by agrias asking

Is "Pub-201603141450" a branch?

(It is a Tag)
I realised that all of my Tags were on the old commits.  Deleting these tags or moving them to the new version of the commit removed the old commits from my history.  Not being that familiar with tags I guess these hold their own history.
I guess if I hadn't had the SSH key issue and followed on with step 7 in https://help.github.com/articles/remove-sensitive-data/ it would have moved my tags over and avoided this issue.


text:
Q: How could I display a non-image file stored in MongoDB(using GridFS) on a web page? I am working on a site that allows a user to upload a document (not an image), which is then stored in MongoDB with GridFS. My question is... is it possible to then embed/display that document for viewing on the site? Everytime I use the createReadStream method, it just downloads the document. I would like it to show the actual document or the document's contents on the webpage, possibly in an iframe. Maybe there is a way to make a url for the document, or access the file another way? Thanks in advance.

A: <ifram

 <iframe src= 'https://www.vanmeegern.de/fileadmin/user_upload/PDF/Web_Development_with_Node_Express.pdf' frameborder="0" width="400px" height="600px"></iframe>

e>


text:
Q: Managing beans in JSF 2.2 on WebSphere 9 Posting this problem / answer as I did not find any other question that was very similar. Lots of related ones but not same scenario.
Was upgrading JSF 2.1 to JSF 2.2 (Mojarra) application for h:fileUpload support. Application runs on WebSphere 9, and after upgrade was encountering problems with dependency injection using JSF Beans.
Reading further I realize that JSF @ManagedBean is to be deprecated and should be migrated to CDI @Named but our application had 627 references to the FacesContext and migrating to a CDI bean would mean updating all those places to either produce a FacesContext when needed, or upgrade JSF to 2.3 and inject the FacesContext where it is needed. This means staying on JSF 2.2 for now.
Here is the bean :
package com.company.customersearch;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

@ManagedBean(name = "customerSearchManager")
@ViewScoped
public class customerSearchManager extends PortletManager{

    private static final long serialVersionUID = -9050481751306478727L;
    private Long customerId;
    private SessionData sessionData;

    @ManagedProperty(value = "#{customerSearchService}")
    private CustomerSearchService service;

    public CustomerSearchManager(){
        this.sessionData = new SessionData((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false));
        if (sessionData.hasSelectedCustomer())
            this.customerId = sessionData.getData().getCustomerId();
    }

...
}

Running on WebSphere 9 was producing a NullPointerException
Error Rendering View[/pages/customer-search.xhtml]
                                 java.lang.NullPointerException
    at com.sun.faces.application.view.ViewScopedCDIEventFireHelperImpl.fireInitializedEvent(ViewScopedCDIEventFireHelperImpl.java:60)
    at com.sun.faces.application.view.ViewScopeContextManager.fireInitializedEvent(ViewScopeContextManager.java:394)
    at com.sun.faces.application.view.ViewScopeManager.processPostConstructViewMap(ViewScopeManager.java:312)
    at com.sun.faces.application.view.ViewScopeManager.processEvent(ViewScopeManager.java:244)
    at com.sun.faces.application.view.ViewScopeEventListener.processEvent(ViewScopeEventListener.java:68)

The NPE is coming out of a CDI related class! Why would we get an NPE inside of ViewScopedCDIEventFireHelperImpl.java when intentionally not using CDI??

A: I don't know if other enterprise containers are this way, but for WebSphere, CDI is enabled by default and is apparently overriding or trying to replace the JSF beans at runtime (??). Wish I understood a bit more on what is happening in the container in this scenario.
Found the following on the IBM site regarding CDI settings:
http://www-01.ibm.com/support/docview.wss?uid=swg21983564
There you can see that there are 2 properties to set on your JVM if you are truly intending to use JSF @ManagedBeans and avoid conflicts with CDI all together. Worked for me.
Set :
com.ibm.ws.cdi.enableCDI = false
com.ibm.ws.cdi.enableImplicitBeanArchives  = false

Hope it helps someone.


text:
Q: PHP replace string value from the specific position to the immediate first special character from the string How to replace string value from the matching part in the specified string.
Exmaple,
$haystack = "2548: First Result|2547: Second Result|2550: Third Result|2551: Fourth Result

Now I want to change starting from 2547: to the first | (pipe) after the starting value.
$result = "2548: First Result|2547: My New String|2550: Third Result|2551: Fourth Result

How can I replace the value of the Specific string from the $haystack variable.
Want to replace value with first matching string to immediate first pipe character in PHP.
In the given string, 2547: Second Result| replace with 2547: My New Value| and remaining part of the string as it is.
Is it possible without using Regular express in PHP and just use common function like strpos() or any other php string function or we can do it easily using preg_replace().

A: you can use like this
$new_value = "My New String";
$array     = explode("|",$haystack);
$new_array = array();
foreach($array as $key)
    $new_array[] = (strstr($key,'2547:'))?"2547: ".$new_value:$key;

print_r(implode("|",$new_array));

/*
Output
2548: First Result|2547: My New String|2550: Third Result|2551: Fourth Result
*/

A: You could use str_replace if you know the full value you want to replace:
$find = "2547: Second Result";
$replace = "2547: My New Value";
$haystack = "2548: First Result|2547: Second Result|2550: Third Result|2551: Fourth Result";

$result = str_replace($find, $replace, $haystack);

print_r($result);

You can also use a loop :
$collection = [];

$find = "2547: Second Result";
$haystack = "2548: First Result|2547: Second Result|2550: Third Result|2551: Fourth Result";

$parts = explode('|', $haystack);

foreach ($parts as $part) {
    [$id, $old_value] = explode(':', $part);

    if (strpos($find, $id) !== false) {
        $part = "{$id}: My New Value";
    }

    $collection[] = $part;
}

$result = implode('|', $collection);

print_r($result);

These are not the only ways to do this...


text:
Q: Why does Gradle->Refresh remove my protobuf source folder from .classpath? I have an Eclipse/Gradle project that looks like the following. One directory for .proto descriptors and one directory for the generated .java files for inclusion in other projects.
    src/main/java
    src/main/proto

I want to add my src/main/proto directory as an Eclipse source folder to make editing easier.
So naturally I add <classpathentry kind="src" path="src/main/proto"/> to my .classpath file. The source folder is added and everything is great until I run Gradle->Refresh which unkindly removes the source folder. My guess is that Gradle doesn't find any .java files in the proto folder and therefore removes the entire folder from .classpath. Is there any way to prevent this?
I have also tried:
<classpathentry kind="src" path="src/main/proto">
  <attributes>
    <attribute name="FROM_GRADLE_MODEL" value="true"/>
  </attributes>
</classpathentry>

from this question without success.

A: so the thing is that gradle will (re)-generate the .classpath file from scratch if you do the refresh. So anything you haven't defined at the gradle level will be lost!
How do you define the src folders in Gradle ?
Try to put the following block into you build.gradle:
sourceSets {
    main {
        java {
            srcDirs 'src/main/proto'
        }
    }
}

This should add 'src/main/proto' to the eclipse classpath as long as the folder contain at least one file!


text:
Q: Get products names in an array in Woocommerce thankyou page I am trying to put the ordered items in a array to pass the values further in woocommerce thank you page. I am currently getting all line item names, sku etc without comma or anything.
foreach ($order->get_items() as $item_id => $item_data) {

    // Get an instance of corresponding the WC_Product object
    $product = $item_data->get_product();
    $product_name = $product->get_name(); // Get the product name

    $item_quantity = $item_data->get_quantity(); // Get the item quantity

    $sku = $product->get_sku();
    $item_total = $item_data->get_total(); // Get the item line total

    // Displaying this data (to check)
    echo 'NAME: '.$product_name.' | Quantity: '.$item_quantity.' | Item total: '. number_format( $item_total, 2 );

}

Current Results

A: This can be done easily with the following:
add_action( 'woocommerce_thankyou', 'thankyou_custom_items_data', 20, 1 );
function thankyou_custom_items_data( $order_id ) {
    // Get an instance of the the WC_Order Object
    $order = wc_get_order( $order_id );

    $items_data = array();

    foreach ($order->get_items() as $item_id => $item ) {

        // Get an instance of corresponding the WC_Product object
        $product = $item->get_product();

        $items_data[$item_id] = array(
            'name'       => $product->get_name(),
            'sku'        => $product->get_sku(),
            'quantity'   => $item->get_quantity(),
            'item_total' => number_format( $item->get_total(), 2 )
        );
    }
    // Testing array raw output
    echo '<pre>'; print_r( $items_data ); echo '</pre>';
}

Code goes in function.php file of the active child theme (or active theme). Tested and works.
You will get a raw output like:
Array (
    [776] => Array (
        [name] => Happy Ninja
        [sku] => HN2563
        [quantity] => 1
        [item_total] => 36.36
    )
    [777] => Array (
        [name] => Patient Ninja
        [sku] => PN2559
        [quantity] => 1
        [item_total] => 29.17
    )
)

Related: Get Order items and WC_Order_Item_Product in Woocommerce 3


text:
Q: How do i call different classes within in a class? So I made two classes, one making a rectangle and one that makes a star, both being Rectangle() and Star() as there class taking in a specific amount of parameters.  My problem is that i have another class called Flag() that takes in a textfile that contain the specific parameters for each class, rectangle has 5 certain parameters, and star has 4.  I need the Flag class to read through the textfile and read through each line of the file, understand that each line is either a rectangle or a star, then draw it.
class Flag(object):
    def __init__(self, f_obj):
        self.f_obj = f_obj
        for line in self.f_obj:
            line.strip()
            if 5 == len(line):
                R = Rectangle(line)
                print(R)
            elif 4 == len(line):
                S = Star(line)
                print(S)

    def draw(self,turtle):
        R.draw(turtle)
        S.draw(turtle)

A: Are you asking about file reading?
Try this:
parts = line.strip().split()
if len(parts) == 4:
    # Star
if len(parts) == 5:
    # Rectangle


text:
Q: Data driven selection in Qt view I am looking for an elegant way to change the selection in a Qt TreeView based on the data of the underlying model. So my dynamic data contains information about the currently active element which should be selected in the TreeView.
Background: I have a setup with a 3d viewer for a bunch of objects and a Qt TreeView that lists the objects. The user should be able to select objects by klicking them either in the TreeView or in the 3d viewer. The 3d viewer is non-Qt code and modifies the data directly and sets the a flag indicating the selection.
I implemented a dataModel and a selectionModel (as I have to synchronize two views on the data).
My current idea is to emit a signal from the dataModel to the selectionModel to modify the selection when the data has changed. But this seems awkward to me...
Is there a recommended Qt way of doing this?


text:
Q: Programmatically created Label will not right-justify Creating a label programatically (i.e. not in designer) won't right-align on my form.
Set lblStatus = StatusForm.Controls.Add("VB.Label", "lbl" & xml(Prop, "column"))
With lblStatus
    .Visible = True
    .Caption = Text
    .Alignment = vbRightJustify
    .WordWrap = False
    .AutoSize = True
    .top = Index * (lblStatus.height)
    .left = MaxWidth - Screen.TwipsPerPixelX * 15
    .Width = StatusForm.TextWidth(Text)
End With

I created three of these controls, but they continue to expand from the left, rather than from the right:

Ideally, I want those labels (surrounded by #) to have their semicolons line up.

A: Since you set AutoSize to true, the width is set to the precise width of the text, leaving no room for alignment.
To layout the text within a fixed width, turn off AutoSize.


text:
Q: Is there such a thing as a pulse relay? Is there such a thing as a pulse relay? So that I do not have to supply constant power for it to remain open, instead just pulse it?

A: Yes, these are called latching relays as Ignacio Vazquez-Abrams noted in his comment.
From Wikipedia: Relay/Latching Relay

A latching relay (also called "impulse", "keep", or "stay" relays) maintains either contact position indefinitely without power applied to the coil. The advantage is that one coil consumes power only for an instant while the relay is being switched, and the relay contacts retain this setting across a power outage.


text:
Q: Are there alternative UIs for Swagger files We are currently using Postman for building and testing our REST endpoints. There are some serious drawbacks in their product when it comes to sharing a collection. Basically you can't use source control for the document because it changes all the guids in json file when you import.
So we're looking at possibly switching to Swagger, the issue with Swagger is that SwaggerUI isn't very user friendly. We like that Postman gives you the ability to break up your collections into folders, and gives you a split screen where you can run a request and see the output.
Are there any third party tools which give a Postman style interface to Swagger files? i.e. easy to find a set of methods for a resource, and to make calls to it.

A: Swagger UI provides a live documentation for your API and you always can customize it to meet your needs. It's not that difficult. From the documentation:

Customize
You may choose to customize Swagger UI for your organization. Here is
  an overview of what's in its various directories:

*

*dist: Contains a distribution which you can deploy on a server or load
  from your local machine.

*dist/lang: Swagger localization.

*lib: Contains JavaScript dependencies which Swagger UI depends on.

*node_modules: Node modules which Swagger UI uses for its
  development.

*src/main/templates: Handlebars templates used to
  render Swagger UI.

*src/main/html: The HTML files, some images and CSS.

*src/main/javascript: Main code.

For additional details, have a look at the Swagger UI documentation.

Themes

*

*Alternatively to the default Swagger UI theme, have a look at this Swagger UI responsive theme, inspired in the Auth0 API explorer.

*You also might like these themes, which are just modifications on the default Swagger UI theme.
Warning
Please note Swagger is not an API testing tool. It's an API documentation tool.

A: So you have two requirements for an API user interface:

*

*easy to find a set of methods for a resource

*make calls to resource methods

It seem SwaggerUI is what you need. See demo here.

*

*You can click Expand Operations and use your browser search function to find a resource or operation by its name.

*You can submit a request, you will be notified when a required field is blank, check a resource request/response model.
Check, for example, the method GET /store/order/{orderId}.
Hit the Try it out! button after entering an orderId and the request will be submitted from the UI.


text:
Q: Entity Framework: Specify foreign key constraint name Is there a way how to specify a name of a foreign key constraint in Entity Framework (v6.1.3)? I mean actual name of DB constraint (like FK_Books_AuthorId), not to specify which column is the foreign key for the given navigation property.
I know you can do it for indices, like:
Property(x => x.AuthorId).HasColumnAnnotation(IndexAnnotation.AnnotationName,
                new IndexAnnotation(new IndexAttribute("IX_Books_AuthorId")));

Is anything similar possible also for foreign key constraints?

A: Based on comments and my further research, it is not currently (EF v6.1.3) possible to set custom name for database foreign key constraint.


text:
Q: Numbers: conditonal highlight based on a date in a different column In numbers, I would like to change the background colour of Column D based on whether the date in Column A is still in the future  (i.e. graying out).
I can get the colour formatting to work on the date column itself ('Date is after the date 0 days ago'), but how can I specify that the rule is based on a different column?
If I specify the above colour rule in 'D' (a pure numeric column), then the colour doesn't change as D doesn't contain a date...

A: This currently isn't possible. Conditional highlighting will only run the condition on the cell that the rule has been applied to.

To change the appearance of a cell based on its cell value, create a conditional highlighting rule.

Source: Add conditional highlighting to cells — Numbers Help for Mac; emphasis mine.
The only exception to this is for conditions where a comparison is required — a second value can be referenced in the rule.

Click  to use a cell reference. A cell reference lets you compare the cell's value to another cell—so, for example, you can highlight a cell when its value is greater than another cell's. Click a cell to select it, or enter its table address (for example, F1).

Source: Add conditional highlighting to cells — Numbers Help for Mac.
As a workaround, you could duplicate (or reference) the column A and place it next to column D, applying the conditional highlighting to that column instead. It won't be highlighting the cell with the data, but it'll give you something to glance at next to the data.


text:
Q: EKEvent eventIdentifier null xcode 9.4 I'm saving an event with XCode and it saves normally. The save returns an ID as well.
When I try to get all the events of my calendar, and then one by one I access the id of the events, it is always nil
Save Code:
-(NSNumber*) save:(id)arg
{
    id val = nil;
    ENSURE_ARG_OR_NIL_AT_INDEX(val, arg, 0, NSNumber);
    EKSpan span = EKSpanThisEvent;
    if (val != nil) {
        span = [TiUtils intValue:val def:EKSpanThisEvent];
    }
    EKEventStore* ourStore = [module store];
    if (ourStore == NULL) {
        DebugLog(@"Could not save event, missing Event Store");
        return NUMBOOL(NO);
    }
    EKEvent* currEvent = [self event];
    if (currEvent == NULL) {
        DebugLog(@"event is missing");
        return NUMBOOL(NO);
    }
    __block NSError * error = nil;
    __block BOOL result;
    TiThreadPerformOnMainThread(^{
        result = [ourStore saveEvent:currEvent span:span commit:YES error:&error];
    }, YES);`enter code here`
    if (result == NO || error != nil) {
        [self throwException:[NSString stringWithFormat:@"Failed to save event : %@",[TiUtils messageFromError:error]]
           subreason:nil
          location:CODELOCATION];
    }
    return NUMBOOL(result);
}

Retreive Code:
- (NSArray *)_fetchAllEventsbetweenDate:(NSDate *)date1 andDate:(NSDate *)date2
{
  if (![NSThread isMainThread]) {
    __block id result = nil;
    TiThreadPerformOnMainThread(^{
      result = [[self _fetchAllEventsbetweenDate:date1 andDate:date2] retain];
    },
        YES);
    return [result autorelease];
  }
  EKEventStore *ourStore = [self ourStore];
  if (ourStore != nil) {
    NSPredicate *predicate = [ourStore predicateForEventsWithStartDate:date1
                                                               endDate:date2
                                                             calendars:[NSArray arrayWithObject:[self calendar]]];
    return [ourStore eventsMatchingPredicate:predicate];
  }
  return NULL;
}


text:
Q: Handling multiple selections result in "Value Relation Widget" in QGIS Using the "Allow multiple selections" in the "Value Relation Widget" results in {value1,value2,...}. But arrays in QGIS are written like ['value1','value2',...].
How do I handle the multiple selection results? For example, if I would get the first entry in my list. With usual arrays, I would use this syntax: array_get('array',0).

A: This may help:
array_get( string_to_array( substr( "array", 2, -1 ) ), 0)

Or
with_variable(
    'arr',
    string_to_array( substr("array", 2, -1)),
    array_get( @arr, 0)
)

A: This is a map with only keys. You can get them using map_akeys('yourmap') which will turn it into an array of all keys.
So your syntax could be  map_akeys('yourmap')[0] or array_get(map_akeys('yourmap'),0)
Similary you could use map_avals('yourmap') to get all values or map_get('yourmap','key') to get a specific value.


text:
Q: Java IndexOutOfBoundsException list error Part of the code:
List<Triangle> triangles = model.getTriangles().stream()
            .map(triangle -> triangle.rotate(orientation))
            .collect(Collectors.toList());

As I understand model.getTriangles the function gets data and constantly streams it into triangles list.
Well, the problem is I have 2 threads on my program. Main thread and extra.
If they both try to simultaneously use that part of the code it throws IndexOutOfBoundsException. Help.


text:
Q: Block spam using .htaccess wildcard for subdomain I have a lot of spam coming from one site with multiple subdomains and currently I am blocking them using individual lines as below
RewriteCond %{HTTP_REFERER} site1.floating-share-buttons.com [NC,OR]
RewriteCond %{HTTP_REFERER} site2.floating-share-buttons.com [NC,OR]
RewriteCond %{HTTP_REFERER} site3.floating-share-buttons.com [NC,OR]
RewriteCond %{HTTP_REFERER} site4.floating-share-buttons.com [NC,OR]
RewriteCond %{HTTP_REFERER} site5.floating-share-buttons.com [NC,OR]

How can I use or what is the wildcard for the sub-domain part so I can achieve the same thing using just one line.

A: Use regex alternation:
RewriteCond %{HTTP_REFERER} (site1|site2|site3|site4|site5)\.floating-share-buttons\.com [NC]

Or else if names are site1,site2,..site5 then:
RewriteCond %{HTTP_REFERER} site[1-5]\.floating-share-buttons\.com [NC]


text:
Q: Using criteria API to compare only hour in ZoneDateTIme I have entity class Order which has property ZonedDateTime deliveryTime. I'd like to extract all orders which delivery time was between e.g 11AM to 2PM for each day.
builder.between(root.<ZonedDateTime>get("deliveryDate"), ??????, ????)
I can limit my result to date boundaries but my goal is to limit delivery hours
Can anyone help?

A: You might use LocalTime#isAfter and LocalTime#isBefore for that:
ZonedDateTime now  = ZonedDateTime.now();
// 2017-04-18T14:54:38.567+01:00[Europe/Dublin]

DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("ha");
LocalTime start = LocalTime.parse("11AM",timeFormatter);
LocalTime end = LocalTime.parse("2PM",timeFormatter);

System.out.println(now.toLocalTime().isAfter(start)); // true
System.out.println(now.toLocalTime().isBefore(end)); // false

I hope this helps.


text:
Q: using ajax and PHP to get json data from geojson I'm using the following php code to get data from geojson file and its working
<?php
header("Access-Control-Allow-Origin: *");
ini_set('display_errors', 'On');
error_reporting(E_ALL);

$data=file_get_contents("countries.geojson");
$data= json_decode($data, true);
$data2= $data["countries"]["country"];
header('Content-Type: application/json; charset=UTF-8');

echo json_encode($data2);
?>

I want to access this data in following ajax code
$.ajax({
    url: "php/main.php",
    type: 'GET',
    dataType: 'json',
    success: function(response) {
        console.log(JSON.stringify(response));
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log("error");
    }
});

right now I'm getting error in console that means it is not getting data from the php code.
How shall I get that data from php file in this ajax call?

A: Try following code and look into console for response or error, returned data is not json formated as expected
    $.get('php/main.php',function(response){
        console.log(response);

    },'JSON').fail(function(xhr,ajaxOption,thrownError){
        console.error(xhr.responseText);
        console.error(thrownError);
    });


text:
Q: Cannot interpret '0' as a data type I try to convert a datafram's column having "object" as datatype into float.
I use the following code:
cam_dev_index_num = cam_dev_index['Access to electricity (% of population)'].astype(int(float()))

But I have this error: "Cannot interpret '0' as a data type"
Could someone explain me what I'm doing wrong please?
Thank you in advance!

A: Try this:
cam_dev_index_num = cam_dev_index['Access to electricity (% of population)'].astype(int).astype(float)
Or the other way around:
.astype(float).astype(int)
Perhaps even only one of the two is needed, just:
.astype(float)
Explanation:
astype does not take a function as input, but a type (such as int).


text:
Q: Issue with setting $PATH directories For some strange reason, I'm getting a "No such file or directory" error for my $PATH variable. I have tried to edit my path using export, changing it from what it was originally to every permutation from a single directory path to the original.
When there is one directory (e.g., export PATH=/bin), I get "/bin: Is a Directory". But once I add more than one directory (e.g., export PATH=/bin:/sbin), I get "No such file or directory".
I'm curious to see what the cause of this issue is!

A: RE; your comment:
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/git/bin:/usr/local/mysql/bin: No such file or directory will be generated if you have a line which says:
$PATH

maybe on its own, or maybe you have $PATH=....  That is, the shell is trying to execute a program named:
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/git/bin:/usr/local/mysql/bin
Lose the $ on the left-hand side.

A: I'm not sure you are using the export variant. You almost certainly have spaces in there and you shouldn't, as per the following transcript:
pax> PATH= /bin
bash: /bin: is a directory

pax> PATH= /bin/sbin
bash: /bin/sbin: No such file or directory

The first is caused because you're setting the path temporarily to an empty string while attempting to run that directory. That's because you can do things like:
pax> xyzzy=1

pax> echo $xyzzy
1

pax> xyzzy=2 bash -c 'echo $xyzzy'
2

pax> echo $xyzzy
1

In other words, it's a way of changing an environment variable for a single command, and having it automatically revert when the command is finished.
The second case is simply because there is no /bin/sbin directory. So it detects that before it complains about the fact that you're trying to run a directory.
Setting a variable in bash is a no-space thing (unless you have spaces in your directory names, in which case they should be quoted). In addition, they need to be colon-sparated. Hence you're looking for things like:
PATH=/bin
PATH=/bin:/sbin
PATH="/bin:/sbin:/directory with spaces in it:$HOME/bin"

A: The export function will only change the variable for the current terminal session.
Write your PATH inside ~/.bash_profile if you want to change it permanently.
For this modification to work you have to close your current terminal and reopen it.


text:
Q: The attribute 'name' already exists DTSX XSD I have dozens of SSIS Packages, extracting numerous columns from various sources. Whenever there is a change in the source data, I need to be able to see which SSIS Package is affected, and it starts to be hard to maintain manually.
Therefore, I would like to read the SSIS Packages stored as .dtsx files to retrieve the relevant information:

*

*input and output columns names and types

*source and destination table names

*type of connection used

With Microsoft providing the XSD for this DTSX format online: Appendix A: Full DTSX XSD, I thought I would be able to create a vb.net class using xsd 'myfile'.xsd /classes /language:vb.
However, having a first look at the .xsd in Visual Studio, I am facing the same warning multiple times:

The attribute 'name' already exists.

I have made sure all the .xsd referenced have proper naming and are in the correct folder.

When trying to use the xsd command in the Visual Studio command prompt, the class actually gets written, but I get a warning:

Schema validation warning: The attribute 'name' already exists. Line 971, position 8.
Schema validation warning: The attribute 'name' already exists. Line 990, position 8.
Schema validation warning: The attribute 'name' already exists. Line 997, position 8.
Schema validation warning: The attribute 'name' already exists. Line 1607, position 14.
Schema validation warning: The attribute 'name' already exists. Line 1620, position 14.
Schema validation warning: The attribute 'name' already exists. Line 1673, position 14.
Warning: Schema could not be validated. Class generation may fail or may produce incorrect results.

Is there anything wrong with the above? Is there any workaround to tackle those warnings?

A: If the code compiles correctly and it works for your purposes, then I think it would be OK to ignore for now. The warnings are being produced due to errors in the schema file itself, so it's not you.
If you run the full DTSX schema through an XSD validator (like Xerces), you get the exact errors that seem to correspond to the warnings being generated by XSD.exe in your own output:

*

*Error for type 'PipelineComponentPropertyType'. Duplicate attribute uses with the same name and target namespace are specified.  Name of duplicate attribute use is 'name'.

*Error for type 'PipelineComponentOutputPropertyType'. Duplicate attribute uses with the same name and target namespace are specified.  Name of duplicate attribute use is 'name'.

*Error for type 'PipelineComponentInputPropertyType'. Duplicate attribute uses with the same name and target namespace are specified.  Name of duplicate attribute use is 'name'.

*Error for type 'PipelineComponentInputColumnPropertyType'. Duplicate attribute uses with the same name and target namespace are specified.  Name of duplicate attribute use is 'name'.

*Error for type 'PipelineComponentOutputColumnPropertyType'. Duplicate attribute uses with the same name and target namespace are specified.  Name of duplicate attribute use is 'name'.

So the issue is basically this: the Pipeline types mentioned above use an attribute group that contains a 'name' attribute, but those same types also locally define another attribute also called 'name' that uses a different type. Here's a diagram of the issue with the duplicate 'name' attributes highlighted:

You could try to fix the schema yourself if you wanted to, by creating another copy of the "DTS:PipelineComponentPropertyAttributeGroup" attribute group and remove the 'name' attribute and use that one on all the PipeLine types that report the warning, but it's a bit difficult to tell what Microsoft meant.
Maybe they meant to override the "DTS:PipelineComponentPropertyAttributeGroup" name attribute with the locally defined one? Or maybe the presence of the "DTS:PipelineComponentPropertyAttributeGroup" attribute group is incorrect and it just shouldn't be there. Hard to tell unless one is intimately familiar with how the DTSX tool works or have an existing DTSX file that might indicate how the 'name' attribute is meant to be properly used.


text:
Q: What is the difference between listViewAdapter.clear() and list.clear()? Okay, I think I have understood it, but I just want to make sure of it. I have got a ListViewAdapter that contains a List.What I wanna do is search thinks in the database and show in a ListView. This piece of code adds an item to my listView.
list.addAll(sqh.DisplayRecords(sqdb));
    listViewAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
    listview.setAdapter(listViewAdapter);
    search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           listViewAdapter.clear();

           list.clear();
           list.addAll(sqh.DisplayRecords(sqdb));
           list.add("another one");

        }
    });

Whit this other piece of code, only clearing the listviewAdapter and adding another item to the list, just, adds the last item, instead of all the items of the list, which should be there.
        list.addAll(sqh.DisplayRecords(sqdb));
    listViewAdapter = new ArrayAdapter( this,android.R.layout.simple_list_item_1,list);
    listview.setAdapter(listViewAdapter);
    search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            listViewAdapter.clear();

            list.add("another one");

        }
    });

Well, I think I understood it while I was writing this. The third one and the first one are pretty the same.
list.addAll(sqh.DisplayRecords(sqdb));
    listViewAdapter = new ArrayAdapter( this,android.R.layout.simple_list_item_1,list);
    listview.setAdapter(listViewAdapter);
    search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            listViewAdapter.clear();

            list.addAll(sqh.DisplayRecords(sqdb));
            list.add("another one");

        }
    });

The listViewAdapter.clear(); would be clearing the list of the adapter, right? Why, when I do just list.clear(), the list view is not cleared?

A: listViewAdapter.clear()

void clear ()
Remove all elements from the list.

And list.clear();
/**
 * Removes all of the elements from this list.  The list will
 * be empty after this call returns.
 */
public void clear() {
    modCount++;

    // clear to let GC do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

If you use in this , it was the same .It used to Removes all of the elements from this list .

A: When you calling list.clear();, you'are removing all of the elements from the list. The list will be empty after this call returns. But your Adapter view isn't change yet. You need to call adapter.notifyDataSetChanged() to refresh the adapter.
In the other case, when you calling listViewAdapter.clear();, the list will be cleared first then the notifyDataSetChanged() called.
You can see the details in ArrayAdapter.clear() source code:
/**
 * Remove all elements from the list.
 */
public void clear() {
    synchronized (mLock) {
        if (mOriginalValues != null) {
            mOriginalValues.clear();
        } else {
            mObjects.clear();
        }
        mObjectsFromResources = false;
    }
    if (mNotifyOnChange) notifyDataSetChanged();
}


text:
Q: Equivalent of a local limit theorem in the large deviation region and asymptotics of a convolution operator Let $\{X_i \}_{i \in \mathbb{N}}$ be a sequence of i.i.d. random variables satisfying $\mathbb{E} X_1 = 0$ and $\mathbb{E} X_1 ^2 < \infty$. Assume that $\{S_n  \}_{n \in \mathbb{N}}$ is a non-lattice random walk, where $S_n = X_1+...+ X_n$. I am wondering whether there is a 'local large deviation theorem' running along these lines:
Theorem. Let $0 < a < b$. Then as $n \to \infty$ uniformly for $r \in [an, bn]$
$$
 \mathbb{P} \{  S_n \in [r,r+1] \} \sim \int\limits_{r} ^{r+1} \kappa _n (x) dx,
$$
where $\kappa _n$ is a function given explicitly.
Similar results are available for $r = o(n)$ in [1], at least for absolutely continuous random variables. This question can also be formulated in terms of the associated convolution operator. Let $a \in L^1$, $a \geq 0$. Define the operator $L$ on some function space by
$$
Lu (x) = \int\limits _{\mathbb{R}} u(y)a(x-y) dy
$$
and set $u_n = L ^n \delta _0$ (or alternatively $u_n = \frac{1}{2 \varepsilon}L ^n \mathbf{1} _\varepsilon$, where $\mathbf{1} _\varepsilon$ is the indicator of $[-\varepsilon, \varepsilon]$ for a small $\varepsilon > 0$). What can  we say about
$$
\int\limits _{r} ^{r+1} u_n (x)dx.
$$
for $r \in [an, bn]$, possibly under some additional assumptions on $a$?
[1]: Richter, W. (1957). Local limit theorems for large deviations. Theory of Probability & Its Applications, 2(2), 206-220.

A: For general classes of bounded pdf's of $X_1$, including pdf's with exponential-like, super-exponential, and sub-exponential tails, your Theorem follows from the considerations in Sections 2.1 and 2.2, with
$$\kappa_n(x)=p_{S_n}(r)e^{-s_0(x-r)},$$
where $p_{S_n}$ is the pdf of $S_n$,
$$s_0:=\sup\{s\ge0\colon m(s)<r/n\},$$
and
$$m(s):=\frac{EX_1e^{sX_1}}{Ee^{sX_1}}.$$
As can also be seen from those considerations, the asymptotics of $p_{S_n}(r)$ will very much depend on how heavy the right tail of the distribution of $X_1$ is.


text:
Q: How to sort date? i have array Like :
<__NSArrayM 0x79f3a4a0>(
{
    "act_date" = "02/03/2015";
    "act_id" = 3;
    "act_name" = test2;
},
{
    "act_date" = "03/03/2015";
    "act_id" = 4;
    "act_name" = test3;
},
{
    "act_date" = "01/03/2015";
    "act_id" = 5;
    "act_name" = test1;
}
)

i want to sort array with date.
i tried this method :
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy"];
NSMutableArray *tempArray = [NSMutableArray array];

for (NSString *dateString in tblList)
{
    NSDate *date = [formatter dateFromString:[dateString valueForKey:@"act_date"]];
    [tempArray addObject:date];
}

   [tempArray sortUsingComparator:^NSComparisonResult(NSDate *date1, NSDate *date2) {
        // return date2 compare date1 for descending. Or reverse the call for ascending.
        return [date2 compare:date1];
    }];

But it returns only array with date, how do I add my all data with sorted date array??

A: You are taking out Date from your array, it is not need, you can still sort array of dictionary by using method like below.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"act_date" ascending:YES];
NSArray *sortedArray = [tblList sortedArrayUsingDescriptors:@[sortDescriptor]];

A: I would do this, if you need to convert the values of "act_date" to an proper NSDate before comparison:
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateFormat:@"MM/dd/yyyy"];

NSArray *_yourOriginalArray = // ...
NSArray *_sortedArray = [_yourOriginalArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary * obj1, NSDictionary * obj2) {
    return [[_dateFormatter dateFromString:[obj2 valueForKey:@"act_date"]] compare:[_dateFormatter dateFromString:[obj1 valueForKey:@"act_date"]]];
}];

then the _sortedArray will have the items sorted.

A: You can use a simple NSSortDescriptor
NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"act_date" ascending:YES selector:@selector(compare:)];
array = [array sortedArrayUsingDescriptors:@[sortDescriptor]];

If you want you can add more descriptor to sort for instance by act_id. The priority is set by the oreder of sort descriptors in the array that you pass to the method -sortUsingDescriptor
[EDIT]
As pointed out by holex act_date is a string and it should be converted to NSdate by using NSDateFormatter. Or you will just sort strings.

A: I am sorting an array of dictionaries with date-
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"act_date" ascending:NO];
[mArrTimeline sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

A: Try this code. May be useful to you.
NSString *strKey = @"act_date";
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:strKey ascending:YES];

NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
tempArr = (NSMutableArray *)[arr sortedArrayUsingDescriptors:sortDescriptors];


text:
Q: No carga imagen en div - Javascript Tengo que realizar la siguiente operación:
Dispongo de un formulario en el cual relleno todos los datos y cuando pulse el botón "Guardar" se me debe cargar el nombre del usuario en un  llamado "listado". Bien, ésto me lo realiza correctamente.
El problema viene cuando quiero profundizar en este div:
Además, se actualizará el listado de personajes en la capa listado,
tomando los datos de la instancia de Repositorio. Para cada
personaje se mostrará:

*

*Una capa de clase "personaje", dentro de la cual tenemos:

*Una imagen que representa el personaje

*El nombre del mismo

Información necesaria para realizarlo, el div se llama "listado" y el código CSS
para ello es el siguiente:
.personaje{
    border:2px solid #00793D;
    width:200px;
    display:inline-block;
    margin:10px;
    background-color:white;
    padding:10px;
}

.personaje img{
    width:150px;
    height:225px;
}

.personaje p{
    text-align:center;
}

¿Por qué no me muestra la imagen en el div listado? ¿Dónde está el error?
Código Javascript clase Repositorio (funciona OK, he realizado casos de prueba):
/* Definición de Repositorio de personajes */
function Repositorio(){
    //Creamos un array de personajes.
    this.arrayPersonajes = new Array();

    //Devuelve el número total de personajes.
    this.getNumero = function(){
        return this.arrayPersonajes.length;
    }

    //Añade un personaje al array.
    this.addPersonaje = function (personaje){
        this.arrayPersonajes.push(personaje);
    }

    //Devuelve el objeto Personaje que coincide con el nombre.
    this.getPersonaje = function (nombre){
        return this.arrayPersonajes[nombre];
    }

    //Muestra los nombres de los personajes creados.
    this.getNombrePersonaje = function (i){
        return this.arrayPersonajes[i].nombre;
    }

    //Elimina el personaje cuyo nombre coincide con el que se pasa como parametro.
    this.eliminaPersonaje = function (nombre){
        for(var i=0; i<this.arrayPersonajes.length; i++){
            if(this.arrayPersonajes[i].nombre == nombre){
                this.arrayPersonajes.splice(i,1);
                return true;
            }
        }
        return false;
    }

    //Comprueba si existe un personaje cuyo nombre se pasa por parámetro.
    this.existePersonaje = function (nombreRecibido){
        for(var i=0; i<this.arrayPersonajes.length; i++){
            var nombre = this.arrayPersonajes[i].nombre;
            if(nombre == nombreRecibido)
                return true; //return this.arrayPersonajes[i];
        }
        return false;
    }
}

Código Javascript clase Formulario (código principal):
/*Creo un objeto/instancia de la clase Repositorio.*/
var miRepositorio = new Repositorio();

/*Registro un evento para cuando termine de cargarse el documento se cargen los eventos necesarios.*/
window.addEventListener('load', iniciar, true);

//Función que se ejecuta tras cargarse el documento y registra el resto de eventos.
function iniciar(){
    //Evento para validar los campos y comprobar que los datos son correctos, así como también guardar un personaje en el repositorio.
    document.getElementById('guardar').addEventListener('click', guardarPersonaje, false);
    //Evento para eliminar un personaje del repositorio. Si coincide el nombre lo eliminamos, sino mensaje de "No encontrado".
    document.getElementById('eliminar').addEventListener('click', eliminarPersonaje, false);
    //Evento para limpiar todos los campos del formulario.
    document.getElementById('limpiar').addEventListener('click', limpiar, false);
}

/******************************************************************************
 **************** FUNCIONES PARA LA COMPROBACIÓN DE LOS CAMPOS ****************
 ******************************************************************************/

//Función que se encarga de validar los campos del formulario.
function guardarPersonaje(evento){
    //Valido los diferentes apartados del formulario. Si todo está OK...
    if (validarCamposText(this) && comprobarNombre() && comprobarImagen() && comprobarEdad() && comprobarColor() && confirm("¿Deseas enviar el personaje?")){
        var nombre = document.getElementById('nombre').value;
        var imagen = document.getElementById('imagen').value;
        var edad = document.getElementById('edad').value;
        var color = document.getElementById('color').value;

        //Creamos el objeto de tipo Personaje con los valores del formulario pasados como parámetros.
        var personaje = new Personaje(nombre, imagen, edad, color);

        //Comprobamos si existe el nombre del personaje en nuestro repositorio...
        if(miRepositorio.existePersonaje(nombre)){
            //Si existe el nombre ya en el arrayPersonajes...
            document.getElementById("informacion").innerHTML="EL PERSONAJE '"+nombre+"' YA EXISTE.";
            limpiar();
        }else{ //Si no existe el nombre del personaje en el repositorio, lo agregamos.
            //Añadimos el personaje al repositorio. Automáticamente lo añade en el array "arrayPersonajes".
            miRepositorio.addPersonaje(personaje);
            //Mostramos los personajes en el div "listado".
            mostrarPersonajes();
            //Si se ha insertado correctamente la información, mensaje de que el personaje fue agregado.
            document.getElementById("informacion").innerHTML="EL PERSONAJE '"+nombre+"' SE HA INSERTADO CORRECTAMENTE.";
            limpiar();
            return true;
        }
    }else{
        //Cancelar el evento por defecto del envío del formulario.
        evento.preventDefault();
        return false;
    }
}

//Función para validar todos los campos input de tipo "text".
function validarCamposText(objeto){
    //La propiedad form del botón enviar contiene la referencia del formulario dónde está ese botón submit.
    var formulario = objeto.form;

    //Recorremos en un array todos los elementos del formulario.
    for (var i=0; i<formulario.elements.length; i++){
        //Eliminamos la clase Error que estaría asignada a algún campo.
        formulario.elements[i].className="";
    }

    //Recorremos en un array todos los elementos del formulario.
    for (var i=0; i<formulario.elements.length; i++){
        //Escogemos los que son de tipo "text" y los que están vacíos...
        if (formulario.elements[i].type == "text" && formulario.elements[i].value.trim()==""){
            //Mostramos en un div, llamado "errores", un mensaje para el usuario de que el campo está vacío.
            document.getElementById("informacion").style.display="block";
            document.getElementById("informacion").innerHTML="EL CAMPO "+formulario.elements[i].name+" NO PUEDE ESTAR VACÍO.";
            formulario.elements[i].className="error";
            formulario.elements[i].focus();
            return false;
        }
    }
    return true;
}

//Función para comprobar que el campo nombre no está vacío.
function comprobarNombre(){
    if (!document.getElementById("nombre").value.trim()==""){
        var nombre = document.getElementById('nombre').value;
        return true;
    }else{
        document.getElementById("informacion").innerHTML="El campo NOMBRE es obligatorio.";
        document.getElementById("nombre").focus();
        return false;
    }
}

//Función para comprobar que el campo imagen no está vacío.
function comprobarImagen(){
    if (!document.getElementById("imagen").value==""){
        var imagen = document.getElementById('imagen').value;
        return true;
    }else{
        document.getElementById("informacion").innerHTML="El campo IMAGEN es obligatorio.";
        document.getElementById("imagen").focus();
        return false;
    }
}

//Función para comprobar que el campo edad no está vacío. Sólo admite dos digitos.
function comprobarEdad(){
    var patron = /^\d{2}$/;
    //Analizamos el patrón.
    if (patron.test(document.getElementById("edad").value)){
        document.getElementById("edad").className="";
        return true;
    }else{
        document.getElementById("informacion").innerHTML="El campo EDAD es obligatorio.";
        document.getElementById("edad").focus();
        return false;
    }
}

//Función, campo color, que comprueba que no se elige la opción por defecto "Elige uno...".
function comprobarColor(){
    if (document.getElementById("color").value != "none"){ //Para comparar con el texto sería: .text="Elige uno..."
        var color = document.getElementById('color').value;
        return true;
    }else{
        document.getElementById("informacion").innerHTML="El campo COLOR debe elegir una opción.";
        document.getElementById("color").focus();
        return false;
    }
}

//Mostramos los personajes en el div listado.
function mostrarPersonajes(){
    var caja_verde = document.getElementById("listado");
    var img = document.createElement("img");
    if(miRepositorio.getNumero()>=0){
        var codigo = "";
        for(var i=0; i<miRepositorio.getNumero(); i++){
            img.setAttribute("src", "./images/"+miRepositorio.getNombrePersonaje(i)+".png");
            var br = document.createElement("br");
            caja_verde.appendChild(br);
            codigo += miRepositorio.getNombrePersonaje(i)+" ";
        }
        caja_verde.innerHTML = codigo;
    }
}

//Función para limpiar todos los campos del formulario: de tipo "text".
function limpiar(){
    var cajas_texto = document.getElementsByTagName("input");
    for(var i=0; i<cajas_texto.length; i++)
        if(cajas_texto[i] && cajas_texto[i].type == "text")
            cajas_texto[i].value="";
}

//Función para eliminar un personaje del repositorio. Lo eliminaremos mediante el campo "Nombre".
function eliminarPersonaje(){
    var nombre = document.getElementById('nombre').value;
    //Si existe el nombre en el array "arrayPersonajes", eliminamos el personaje (el objeto completo).
    if(miRepositorio.eliminaPersonaje(nombre)){
        document.getElementById("informacion").innerHTML="EL PERSONAJE '"+nombre+"' SE HA ELIMINADO DE LA TIENDA.";
        //Actualizamos los discos que tenemos en la tienda.
        mostrarPersonajes();
        limpiar();
        return true;
    }else{
        //Si NO EXISTE ningún personaje con ese titulo/nombre, mensaje.
        document.getElementById("informacion").innerHTML="NO EXISTE NINGUN PERSONAJE CON EL NOMBRE '"+nombre+"'.";
        document.getElementById("nombre").focus();
        return false;
    }
}

Código HTML necesario del div:

    Nombre del personaje
    <input type="text" name="nombre" id="nombre" />

    Imagen
    <input type="text" name="imagen" id="imagen" />

    Todavía no tienes ningún personaje.

Debería quedar una imagen como el ejemplo:

A: En esta función veo que creas una eqtiqueta img y br,   incrustas la etiqueta br, pero no veo donde incrustas la etiqueta img....
me refiero a que faltaría esta linea: caja_verde.appendChild(img); y crear la eqtiqueta img dentro del bucle...
function mostrarPersonajes(){
        var caja_verde = document.getElementById("listado");

        if(miRepositorio.getNumero()>=0){
                var codigo = "";
                for(var i=0; i<miRepositorio.getNumero(); i++){
                 var img = document.createElement("img");
                img.setAttribute("src", "../images/"+miRepositorio.getNombrePersonaje(i)+".png");
                var br = document.createElement("br");
                caja_verde.appendChild(br);
                caja_verde.appendChild(img);
                codigo += miRepositorio.getNombrePersonaje(i)+" ";
            }
            caja_verde.innerHTML = codigo;
        }
    }


text:
Q: How does input value work? There is a input tag in a webpage. When I inspect it:
<input type="text" onmouseover="this.select();" readonly="" value="<embed src="https://imgcache.qq.com/tencentvideo_v1/playerv3/TPout.swf?max_age=86400&v=20161117&vid=d0380tpvuqx&auto=0" allowFullScreen="true" quality="high" width="480" height="400" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed>">

But when I view its' page source:
<input type="text" onmouseover="this.select();" readonly r-attr="{value:shareHtml}">

How does it work? And how can I get the input value by nokogiri since the parsed result looks like this:
#<Nokogiri::XML::Element:0x3fcc71309c60 name="input" attributes=[#<Nokogiri::XML::Attr:0x3fcc71309be8 name="type" value="text">, #<Nokogiri::XML::Attr:0x3fcc71309bd4 name="onmouseover" value="this.select();">, #<Nokogiri::XML::Attr:0x3fcc71309bc0 name="readonly" value="readonly">, #<Nokogiri::XML::Attr:0x3fcc71309bac name="r-attr" value="{value:shareHtml}">]>

A: You can't get the value with Nokogiri alone, however you can get it if you use a tool that is loading the javascript before you get the html. One tool like this would be Selenium, which is using the browser to load the page first.
driver = Selenium::WebDriver.for :firefox
driver.get("https://www.google.com")

You need to wait for some change on the page, to know that the js has finished.
You can do that by waiting for some element with a certain css tag has appeared:
driver.find_element(:css, '#some-id')

Or just wait a set anount of time:
sleep(2)

After the javascript have changed the content of the page, you get the new html source:
html_source = driver.page_source
driver.quit

Then you can use Nokogiri to parse the html:
doc = Nokogiri::HTML(html_source)
doc.at('input')['value']


text:
Q: SQL: alter default select order (w/o ORDER BY clause) when it is a sensitive data
I'm working on a tokenization system to store sensitive data in a key value table,
but the default select order can be a weak link of the chain if it reproduce the order of the INSERT queries. I think that it much easier to understand with an example.
Suppose that we have this data:

FirstName: Bob LastName: Smith Yearly income: $56000

We associate for every value a random token:

58217 => Bob 79174 => Smith 37142 => $56000

We have two tables on two different databases:
the first one has the columns "FirstName", "LastName" and "YearlyIncome" and we store on it a row with values 58217, 79174 and 37142;
the second one has the columns "Token" and "PlainText" where we store three records:

58217, "Bob" 79174, "Smith" 37142, "$56000"

The purpose of tokenization is that if an intruder can read just one database, he cannot pull out any useful information.
BUT: if a simple SELECT * FROM Tokens give the records in the same order we inserted them, it's really simple to read that Bob Smith has an yearly income of $56000. Just read from top to bottom.
I know that SQL doesn't guarantee that the default select order reflects the insert order, but really often it does, and in this context it's a problem, so the question is:
there is a way to shuffle the default order or - better - to shuffle how the data is physically stored on the database?
I know that we can dump all data, shuffle it and then re-insert it with the new order but I think it's a too much expensive way to do it;
and I'm sure that there is already a smooth solution but I didn't found find anything useful on Internet, so here I am :)
Thank you very much!

A: Some RDBMS solutions have the concept of "clustered index". A clustered index stores records in the order of the index, so if your "token" column is truly random, creating a clustered index on that column will probably achieve what you want. Though, as @damien_the_unbeliever writes, the behaviour is non-deterministic, so there's no guarantee.
You should be aware that this will create possible performance challenges - by re-ordering the table every time you create a new record, you may experience a noticable slowdown.
I would also question whether the significant additional work and complexity you're introducing really gives you any security benefit. By definition, there must be a way of combining data from the two databases; I imagine that's because you're creating a SQL user you are "confident" cannot be hacked; if you are "confident", why not store the data in that user's database? You might also look at database-native encryption.
Finally, tokenizing has a specific meaning in computer science, and it's not apparently what you are using.


text:
Q: Flashing code from IDE to microcontroller How does code download from PC to flash memory controller work? I mean what documents do IDE designers refer while designing this kind of software.
Are there any standard documents available for ST Microelectronics if one wishes to design a new IDE?

A: Assuming you are talking about the ST32X series MCU's and using a serial connection from your IDE/PC then read this first, then the bootloader (over serial) document.
If you want to use other transfer Phy's then you need to do more research:
Application Notes:
– AN3154: CAN protocol used in the STM32 bootloader
– AN3155: USART protocol used in the STM32 bootloader
– AN3156: USB DFU protocol used in the STM32 bootloader
– AN4221: I2C protocol used in the STM32 bootloader
– AN4286: SPI protocol used in the STM32 bootloader
The "Flash Programmer" is just a piece of code in the client that offers a protocol over your selected Phy interface. Though this is simple stuff to look up, you really have no excuse for not being able to find it on your own.


text:
Q: .htaccess: "redirect permanent" with fallback to a "RewriteRule" i have a webshop where we switch the subdirectory. From "/shop" to the root "/". Also some Product- and category-names change.
I want to redirect some specific URLs to newer ones. For Example:
www.domainname.de/shop/product_abc to www.domainname.de/product_abc_v2
For this, I use the Redirect Permanent declaration in the .htaccess File.
In the next Step I want a Fallback for all other URL´s which looks like this:
www.domainname.de/shop/XXXXX.
So i write this Rewrite Rule:
RewriteCond %{REQUEST_URI} ^/shop/(.*)
RewriteRule ^(.*)$ http://www.domainname.de/ [r=301,L]
RewriteRule ^(.*)/$ $1 [R=301,L]

Now my problem: I put the Rewrite Rule to the bottom of the .htaccess File so that the Redirect Permanent-Code would be used before the Rewrite Rule is used. But anyway the Rewrite Rule is always taken. Is there any solution for this problem?!
Thanks a lot!

A: The solution is to use only mod_rewrite. When you mix mod_alias (Redirect Permanent) and mod_rewrite (RewriteRule) directives together, both modules will get applied to every URL, and in cases where both get applied, you end up with some unexpected behavior.
The first thing you need to do is change the Redirect to Rewrite:
Redirect Permanent /shop/product_abc /shop/product_abc_v2

to:
RewriteRule ^shop/product_abc(.*)$ /shop/product_abc_v2$1 [L,R=301]

Then you need to make sure the new rule is in the right place. The order matters with rewrite rules.


text:
Q: I need to know if it is possible to create a SSRS report as defined I have a query with 3 parameters that a user should be able to define:
AND (ORION_SCHED.TRIP.DATE_TIME = '09/11/2012')
AND (ORION.CUST.COUNTRY = 'BE')
AND (ORION_SCHED.TRIP.ID_SHIFT ='1')

*

*DATE_TIME should be a datepicker

*COUNTRY dropdown with defined values

*ID_SHIFT dropdown with defined values

I guess this isn't an issue?
The result of this query will return the dataset

My actual question: I want the result to be presented in this way

So always 3 blocks of data next to each other, the data of every block is the result of the query filtered down on the column TRUCK_ID (a sub-select of the returned dataset)
The empty cells per block are a nice to have, these are non-unique values per TRUCK_ID that I don't wish to be repeated on every line, but like I said a nice to have.

A: I would add a new column to the query that returned 1,2 or 3 (for each different TRUCK_ID. Then I would use 3 Tablix (one per column on your report) and filter the data by the new column you added on the query.
Then you just group on the TruckID on each tablix and play around with the format. It should work.


text:
Q: Update the results of a SELECT statement Oracle lets you update the results of a SELECT statement.
UPDATE (<SELECT Statement>)
SET <column_name> = <value>
WHERE <column_name> <condition> <value>;

I suppose that this could be used for updating columns in one table based on the value of a matching row in another table.
How is this feature called, can it efficiently be used for large updates, does it work when the SELECT joins multiple tables, and if so, how?

A: I haven't seen a formal name for this.  The Oracle SQL Reference just refers to updating a subquery.  I tend to think of it as a form of "view updating", with the subquery being in in-line view.
Yes, it works when a number of tables are joined, but subject to the rules of view updating. This means that only one of the view's base tables can be updated, and this table must be "key-preserved" in the view: i.e. its rows should only be able to appear once in the view.  This requires that any other tables in the view (subquery) are referenced via foreign key constraints on the table to be updated.
Some examples may help.  Using the standard Oracle EMP and DEPT tables, with EMP.EMPNO being defined as the primary key of EMP, and EMP.DEPTNO being defined as a foreign key to DEPT.DEPTNO, then this update is allowed:
update (select emp.empno, emp.ename, emp.sal, dept.dname
        from   emp join dept on dept.deptno = emp.deptno
       )
set sal = sal+100;

But this is not:
-- DEPT is not "key-preserved" - same DEPT row may appear
-- several times in view
update (select emp.ename, emp.sal, dept.deptno, dept.dname
        from   emp join dept on dept.deptno = emp.deptno
       )
set dname = upper(dname);

As for performance: the optimiser will (must) identify the base table to be updated during parsing, and joins to other table will be ignored since they do not have any bearing on the update to be performed - as this AUTOTRACE output shows:
SQL> update (select emp.ename, emp.sal, dept.dname
  2              from   emp join dept on dept.deptno = emp.deptno
  3             )
  4      set sal = sal-1;

33 rows updated.

Execution Plan
----------------------------------------------------------
Plan hash value: 1507993178

------------------------------------------------------------------------------------
| Id  | Operation           | Name         | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------
|   0 | UPDATE STATEMENT    |              |    33 |   495 |     3   (0)| 00:00:01 |
|   1 |  UPDATE             | EMP          |       |       |            |          |
|   2 |   NESTED LOOPS      |              |    33 |   495 |     3   (0)| 00:00:01 |
|   3 |    TABLE ACCESS FULL| EMP          |    33 |   396 |     3   (0)| 00:00:01 |
|*  4 |    INDEX UNIQUE SCAN| SYS_C0010666 |     1 |     3 |     0   (0)| 00:00:01 |
------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   4 - access("EMP"."DEPTNO"="DEPT"."DEPTNO")

(Note that table DEPT is never accessed even though DEPT.DNAME appears in the subquery).

A: Thanks for comments, I thought this was standard Sql... :(
For Oracle you can write an update on a table where you retrieve information with a join like:
UPDATE (
    SELECT *
    FROM table1 t1
    LEFT JOIN table2 t2 ON t2.t1id = t1.ID
) SET t1.col1 = t2.col2

For Sql Server, it's:
UPDATE t1
SET col1 = t2.col2
FROM table1 t1
LEFT JOIN table2 t2 on t2.t1id = t1.id

If anyone knows a way to do this that works on Oracle, Sql Server and MySql I'd be interested.

A: The form you mention has no specific name AFAIK. Just updating the result of a select statement.
There is another form called Correlated update (with single or multicolumn update)
UPDATE TABLE(<SELECT STATEMENT>) <alias>
SET <column_name> = (
  SELECT <column_name>
  FROM <table_name> <alias>
  WHERE <alias.table_name> <condition> <alias.table_name>
);

The multicolumn form
...
SET (<column_name_list>) = (
  SELECT <column_name_list>
...

There is also a from which also returning of values called Update with returning clause
And some specifics for updates with nested tables. Best is to check at least this two pages
Oracle® Database SQL Language Reference SELECT
Oracle® Database SQL Language Reference UPDATE


text:
Q: navbar-fixed-top bootstrap class disables vertical scrolling on page. I am making my first website using bootstrap (see code below). I have added the navbar-fixed-top class to my page in order to make the navigation bar stick to the top when scrolling down. But instead this class completely disables the possibility to scroll down the page. There simple is no vertical scroll bar on the right side visible anymore. What could the reason behind this be and how can I fix this?
Thanks in advance!
Stijn

              Logo

1

2

3

4

5

<form action="#">
                            <button class="btn btn-default btn-primary navbar-btn">Apply</button>

A: Easy fix. You did not close your tags appropriately. Be sure that you are closing tags as you open them or else you will run into this problem. This is what your HTML should look like:
HTML:

 Logo

1

2

3

4

5

                                <form action="#">
                                    <button class="btn btn-default btn-primary navbar-btn">Apply</button>
                                </form>

Summary
You did not close your form tag, an li tag, several div tags, and your nav tag. Whenever you went to put something in the "body" of the document, it would still think that it was part of the navigation bar, which then it would not render it. Just close your tags next time :) I have also left a JSFiddle below of an example to show you that this was the only issue.
DEMO


text:
Q: getting : java.sql.SQLException: Unknown system variable 'language' spring boot I am beginning with spring data jpa and i have configured all spring app. in which my bootstrap class is
@SpringBootApplication
@ComponentScan("com.ticket.booking")
@EnableJpaRepositories("com.ticket.booking.dao")
@EntityScan("com.ticket.booking.entity")
public class TicketBookingManagementApplication {

public static void main(String[] args) {
    SpringApplication.run(TicketBookingManagementApplication.class, args);
}

}
my controller
 @RestController
 @RequestMapping(value="/api/ticket")
 public class TicketController {

@Autowired
private TicketService ticketService;

@GetMapping(value="/")
public String welcome(){
    return "Welcome to Ticket Booking Systems";
}

@PostMapping(value="/add")
public Ticket createTicket(@RequestBody Ticket ticket){
    return ticketService.createNewTicket(ticket);
}

@GetMapping(value="/get/{ticketId}")
public Ticket getTicket(@PathVariable ("ticketId") Integer ticketId){

    return ticketService.getTicketById(ticketId);
}

}
service and repository
 @Service
 public class TicketService {

@Autowired
private TicketDao ticketDao;

public Ticket createNewTicket(Ticket ticket) {
    // TODO Auto-generated method stub
    return ticketDao.save(ticket);
}

public Ticket getTicketById(Integer ticketId) {
    // TODO Auto-generated method stub
    return ticketDao.findOne(ticketId);
}

}

public interface TicketDao extends CrudRepository<Ticket, Integer>{}

in pom.xml i have added
   <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

It uses  mysql-connector-java-5.1.46.jar:5.1.46 and it maps req successfully but while running app i am getting error like
  java.sql.SQLException: Unknown system variable 'language'

and exporting schema to database

A: update your mysql-connector version. it will solve your problem.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>

properties:
spring.datasource.url=jdbc:mysql://localhost/schema_name
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

A: I am posting this answer because somebody might get benefited from this.
In my case, I was working with Spring-boot so the dependency in pom.xml was
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

So spring boot was taking some default dependency version from Spring boot parent which was different from my System installed mysql-server version 5.1.22 so that was the reason behind that error.
So to resolve this error I overridden the version by specifying manually like below.
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.22</version>
</dependency>

and it worked.


text:
Q: Exception: type '_InternalLinkedHashMap' is not a subtype of type 'List' in type cast im tryin to display data from json api inside my flutter app , My Error :
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

My Method:
List _loadedAkhbar = [];

  Future<void> _fetchData() async {
    const apiUrl = 'myapi';

    HttpClient client = HttpClient();
    client.autoUncompress = true;

    final HttpClientRequest request =
        await client.getUrl(Uri.parse(apiUrl + '/${widget.id}'));
    print(apiUrl + '/${widget.id}');
    request.headers
        .set(HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
    final HttpClientResponse response = await request.close();

    final String content = await response.transform(utf8.decoder).join();
Map<String, dynamic> data = jsonDecode(content);

    setState(() {
      _loadedAkhbar = data as List ;
    });
  }

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

Json Format

Any Solution to solve it Please

A: Your api response is Map and your casting your map to List and that cause error, instead of this:
List _loadedAkhbar = [];
Map<String, dynamic> data = jsonDecode(content);

    setState(() {
      _loadedAkhbar = data as List ;
    });

Try this:
    Map _loadedAkhbar = {};
setState(() {
      _loadedAkhbar = jsonDecode(content);
    });

A: This line is casting your data to a List, when it's actually a Map:
_loadedAkhbar = data as List; // ERROR

You probably want to change the declaration of _loadedAkhbar:
Map<String, dynamic>? _loadedAkhbar;

And remove the cast:
_loadedAkhbar = data;


text:
Q: Remove last n characters from -print0? Currently I have:
@find . -type f -name "img*_01.png" -print0 | python script.py -f {}
is there a way to trim the last few chars like this?
@find . -type f -name "img*_01.png" -print0 | python script.py -f {}.rightTrim(n)

A: Assuming you meant:
find . -type f -name "img*_01.png" -print0 |
  xargs -r0I{} python script.py -f {}

That can't be done with xargs, as in xargs has no rightTrim() operator. You can either do away with xargs and do something like (bash, zsh syntax):
find . -type f -name "img*_01.png" -print0 |
  while IFS= read -rd '' file; do
    python script.py -f "${file%?????}"
  done

Or keep xargs but invoke a shell to do the trimming:
find . -type f -name "img*_01.png" -print0 | xargs -r0 sh -c '
  for file do
    python script.py -f "${file%?????}"
  done' sh

Though in that case, you might as well use the standard -exec {} + syntax:
find . -type f -name "img*_01.png" -exec sh -c
  for file do
    python script.py -f "${file%?????}"
  done' sh {} +

Or (if you don't otherwise also need the full filename), pipe the output to some command that trims the last 5 characters of each filename:
sed -zE 's/.{5}$//' # assuming recent GNU sed

or
awk -v RS='\0' -v ORS='\0' '{print substr($0,1,length-5)}'

(assuming GNU awk or recent versions of mawk).
On GNU systems, you can also do it with basic one-task utilities with:
tr '\n\0' '\0\n' | rev | cut -c 6- | rev | tr '\n\0' '\0\n'

And there's always perl:
perl -0 -pe 's/.{5}$//'
perl -0 -lpe 'chop;chop;chop;chop;chop'
perl -0 -lpe 'substr($_,-5,5,"")'


text:
Q: Shortcut for cloning a tab In Opera how can I define a shortcut for cloning a tab? Currently I right click on a tab select clone tab

A: Assuming you mean a keyboard shortcut, go to Preferences > Advanced > Shortcuts, and edit your keyboard setup. If you haven't got a custom one yet, you may want to select the "Opera Standard" one, hit "Duplicate", and select the copy (this bit isn't obvious, duplicating a setup doesn't automatically select it), and click "Edit...". (You may want to rename it, too, just to make sure you'll always know it's your custom one.)
In the "Edit Keyboard Setup" dialogue, expand and select "Browser Window" and click the "New..." button to the right. Type your desired shortcut (space-separated, with the main key before the modifiers - for instance, "d shift ctrl", or have a look at some of the other key definitions in there, especially if you're on a Mac) in the field on the left, and the action "Duplicate page" on the right (double-click to edit a field).
Once you've added the shortcut, click "OK" to close the dialog, and, making sure you've selected your custom Keyboard setup, click "OK" to close the Preferences. Your keyboard shortcut (Ctrl+Shift+D in the example) should now duplicate the current tab.
If you want a mouse gesture rather than a keyboard shortcut, it's quite similar - duplicate and edit your custom mouse setup to add a new gesture and set "Duplicate page" as the action to have the mouse gesture clone your tab.


text:
Q: double value variable in windows command line i would like to write 10 random double values in a file using Windows command line.
What is the best way to do it? Google gives no answer how to create a double variable in cmd.


text:
Q: Как обновить url после переноса сайта, wordpress Перенёс сайт на другой домен, и некоторые ссылки на изображения остались со старого сайта.
В phpmyadmin делал замену всех ссылок в таблицах wp_posts, wp_options, wp_postmeta.
Ссылки остались в сериализованных данных.
Подскажите, как правильно восстановить эти ссылки?
Эти данные скорее всего были сохранены плагинами в сериализованном виде.
И как лучше сохранять данные при разработке, чтобы не было таких ссылок со старого сайта?


text:
Q: BZip2 compressed input for Apache Flink I have a wikipedia dump compressed with bzip2 (downloaded from http://dumps.wikimedia.org/enwiki/), but I don't want to unpack it: I want to process it while decompressing on the fly.
I know that it's possible to do it in plain Java (see e.g. Java - Read BZ2 file and uncompress/parse on the fly), but I was wondering how do it in Apache Flink? What I probably need is something like https://github.com/whym/wikihadoop but for Flink, not Hadoop.

A: It is possible to read compressed files in the following formats in Apache Flink:
org.apache.hadoop.io.compress.BZip2Codec
org.apache.hadoop.io.compress.DefaultCodec
org.apache.hadoop.io.compress.DeflateCodec
org.apache.hadoop.io.compress.GzipCodec
org.apache.hadoop.io.compress.Lz4Codec
org.apache.hadoop.io.compress.SnappyCodec

As you can see from the package names, Flink does this using Hadoop's InputFormats.
This is an example for reading gz files using Flink's Scala API:
(You need at least Flink 0.8.1)
def main(args: Array[String]) {

  val env = ExecutionEnvironment.getExecutionEnvironment
  val job = new JobConf()
  val hadoopInput = new TextInputFormat()
  FileInputFormat.addInputPath(job, new Path("/home/robert/Downloads/cawiki-20140407-all-titles.gz"))
  val lines = env.createHadoopInput(hadoopInput, classOf[LongWritable], classOf[Text], job)

  lines.print

  env.execute("Read gz files")
}

Apache Flink has only build-in support for .deflate files. Adding support for more compression codecs is easy to do, but hasn't been done yet.
Using HadoopInputFormats with Flink doesn't cause any performance loss. Flink has build-in serialization support for Hadoop's Writable types.


text:
Q: use  in  cause DOM errors vue-bootstrap and nuxt js this is my code for nav menu :
<b-navbar toggleable="lg" class="navbar navbar-expand-lg navbar-light">
  <b-navbar-toggle target="nav-collapse" class="mx-auto my-0"></b-navbar-toggle>
  <b-collapse id="nav-collapse" is-nav>
    <b-navbar-nav>
        <b-nav-item to="/">home</b-nav-item>
    </b-navbar-nav>
    <b-dropdown id="dropdown-1" text="categories">

        <b-dropdown id="dropdown-2" :text="category.title" v-for="category in settings.categories"
        :key="category.id">
            <b-dropdown-item :to="`/category/`+child.id+`/`+child.slug"  v-for="child in
            category.childs" :key="child.id">{{ child.title }}</b-dropdown-item>
        </b-dropdown>
    </b-dropdown>
  </b-collapse>
</b-navbar>

but i get so many DOM error in nuxt . i'm using bootstrap-vue . i want to use "b-dropdown" in nav bar but it cause DOM errors . how can i get rid of these errors ?

why i'm using "b-dropdown" in wrong place ? well , see this question : bootstrap-vue multi level drop down
if i remove (b-dropdown id="dropdown-1" ... ) tag , errors will go away !

A: First of all, it's not an error, it's a warning. It has to do with that component not being compatible with SSR so the server side content doesn't match the client side.
You should try wrapping the code between <no-ssr/> tags and that should make it work fine.
<no-ssr>
<b-navbar toggleable="lg" class="navbar navbar-expand-lg navbar-light">
  <b-navbar-toggle target="nav-collapse" class="mx-auto my-0"></b-navbar-toggle>
  <b-collapse id="nav-collapse" is-nav>
    <b-navbar-nav>
        <b-nav-item to="/">home</b-nav-item>
    </b-navbar-nav>
    <b-dropdown id="dropdown-1" text="categories">

        <b-dropdown id="dropdown-2" :text="category.title" v-for="category in settings.categories"
        :key="category.id">
            <b-dropdown-item :to="`/category/`+child.id+`/`+child.slug"  v-for="child in
            category.childs" :key="child.id">{{ child.title }}</b-dropdown-item>
        </b-dropdown>
    </b-dropdown>
  </b-collapse>
</b-navbar>
<no-ssr/>

For more information check this github issue.

A: It's a current bug in Bootstrap-Vue (version 2.14.0 to the current version 2.16.0).
However based on this comment, there's a workaround, which involves using a slot instead of the text prop.
So instead of this
<b-dropdown text="Category" ... >
  <!-- Content -->
</b-dropdown>

You would write this
<b-dropdown ... >
  <template v-slot:button-content>
    Category
  </template>

  <!-- Content -->
</b-dropdown>


text:
Q: Textbox and Class Have trouble connecting exception to textbox input - Program should only accept "IL", "MO" or "WI" - But it's accepting every input.  Everything I tried I'm hitting a brick wall - I know the solution is there, I just need some help.  Thanks
Form Codes
Public Class Form1
Dim packages(4) As Packages
Dim pkg As Integer = 0

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    packages(0) = New Packages("Z111", "Eau Claire", "WI")
    packages(1) = New Packages("Z121", "Vicki Vale", "IL")
    packages(2) = New Packages("Z131", "Sammy Davis", "MO")
    packages(3) = New Packages("Z141", "Jon Smith", "IL")
    packages(4) = New Packages("Z151", "Suzie Cassidy", "WI")

    DisplayInfo()

End Sub

Sub DisplayInfo()

    txtID.Text = packages(pkg).PackageID
    txtCity.Text = packages(pkg).DestinationCity
    txtState.Text = packages(pkg).DestinationState
    lblPackageCount.Text = "Package #   " & pkg + 1

End Sub

Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
    pkg = 0
    DisplayInfo()
End Sub

Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
    If pkg > 0 Then
        pkg -= 1
        DisplayInfo()
    End If
End Sub

Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
    If pkg < packages.Length - 1 Then
        pkg += 1
        DisplayInfo()
    End If
End Sub

Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
    pkg = packages.Length - 1
    DisplayInfo()
End Sub

Private Sub btnSaveChanges_Click(sender As Object, e As EventArgs) Handles btnSaveChanges.Click

    Try

        packages(pkg).PackageID = txtID.Text
        packages(pkg).DestinationCity = txtCity.Text
        packages(pkg).DestinationState = txtState.Text

    Catch ex As Exception

        MessageBox.Show(ex.Message)

    End Try

End Sub

End Class
Class Codes
Public Class Packages
Private packID As String
Private desCity As String
Private desState As String

Sub New(id As String, city As String, state As String)
    packID = id
    desCity = city
    desState = state
End Sub

Public Property PackageID As String
    Get
        Return packID
    End Get
    Set(value As String)
        packID = value
    End Set
End Property

Public Property DestinationCity As String
    Get
        Return desCity
    End Get
    Set(value As String)
        desCity = value
    End Set
End Property

Public Property DestinationState As String
    Get
        Return desState
    End Get
    Set(value As String)
        If desState = "IL" Then
            desState = value
        ElseIf desState = "WI" Then
            desState = value
        ElseIf desState = "MO" Then
            desState = value
        Else
            Throw New Exception("Can not deliver to this state")
        End If
    End Set
End Property

End Class

A: Your immediate problem is you're checking the property value instead of the passed value.  Something like this should work:
Set(value As String)
    'This creates a temporary string array of available states and checks if _
     the value passed is contained in the array
    If {"IL","WI", "MO"}.Contains(value)Then
        desState = value
    Else
        Throw New Exception("Can not deliver to this state")
    End If
End Set

If this is something you may need to change you could make the array a property.


text:
Q: How can I count no.of strings executed for fizzbuzz in range(1,500):
if (fizzbuzz % 3==0 and fizzbuzz % 5==0:
  print(fizzbuzz)
else:
  print(not divisible)

Now, how to see how many fizzbuzz's are there with exact count.

A: You simply need to update a counter. Adding to the code you've shown and properly indenting:
c = 0

for fizzbuzz in range(1,500):
  if (fizzbuzz % 3==0 and fizzbuzz % 5==0:
    print(fizzbuzz)
    c += 1
  else:
    print(not divisible)

print(c)

Of course, you could also just increment your range by 15, and start with 15:
c = 0

for i in range(15, 500, 15):
  print(fizzbuzz)
  c += 1

print(c)