text:
Q: How to match a hexadecimal value in liquid templates with regex? Desired result
Content editors can enter hexadecimal values in Shopify for a background-color. How can you check with Liquid template's control flow if a given input is a valid hexadecimal?
The regex that needs to be implemented:
^#(?:[0-9a-fA-F]{3}){1,2}$

The Liquid snippet where it should be added:
<div class="a-module" style="background-color: {{ bg_color }};">
  ...
</div>

The variable bg_color may only be a hexadecimal including the pound # character.
How can above be achieved with regex?
Other solutions?
If this is not possible what are other methods to match a string in liquid templates?
Research
I could not find much about regex in liquid templates.
There is this issue: Regex for matching a tag in a Liquid template : ">" inside html tag
But I do not understand how it is to be implemented.

A: What about create your own filter. And in this filter checking hexadecimal.
/^#[0-9a-f]{3,6}$/igm

https://github.com/Shopify/liquid/wiki/Liquid-for-Programmers#create-your-own-filters

A: There is no regex in Shopify liquid, so there is no way to check it that way.
A better approach will be to use one of the color filters.
You can do something like this:
{% assign is_color = bg_color | color_to_rgb  %}
{% if is_color %}
  It's color
{% endif %}

Where if the color is valid it will return a rgb output, but if it's not it will return a null result making the variable false.
If you really need to use regex, the only option is to rely on Javascript and handle it once the DOM is ready.


text:
Q: Code (using Patch function) to save update from PowerApps to SQL table not working this is my code in PowerApps:
OnSelect = Patch(ProjectTrackerPowerApps, {ProjectTrackerID: First([@PowerBIIntegration].Data).ProjectTrackerID, 'Meeting Notes':TextInput1.Text } )
where ProjectTrackerPowerApps is the SQL table name, and "Meeting Notes" is the field in PowerApps that is being edited and the edits are to be read back to the SQL table using the OnSelect Code.
But it's not working, i.e. I don't see the changes in the SQL table.
I also tried this other code - slightly different than the 1st but it also didn't work:
OnSelect = Patch(ProjectTrackerPowerApps, defaults(ProjectTrackerPowerApps), {Field:Screen1.Selected.ProjectTrackerID})
Can you please review the code and help me correct so it works?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Click on icon in a JTextField and clear its content I am trying to create a JTextField with an image and a hint. The function of the textfield is a search field to search some books. Now, I like to go a little bit further. I would like to give the image a function. For example, if I click on the image the text in the textfield should be cleared.
To achieve this implementation I created a new class and extended it with JTextField.
This is the code:
public class JSearchTextField extends JTextField implements FocusListener {

/**
 *
 */
private static final long serialVersionUID = 1L;
private String textWhenNotFocused;
private Icon icon;
private Insets dummyInsets;
private JTextField dummy;

public JSearchTextField() {
    super();

    Border border = UIManager.getBorder("TextField.border");
    dummy = new JTextField("Suchen...");
    this.dummyInsets = border.getBorderInsets(dummy);

    icon = new ImageIcon(JSearchTextField.class.getResource("/images/clearsearch.png"));
    this.addFocusListener(this);

}

public JSearchTextField(String textWhenNotFocused) {
    this();
    this.textWhenNotFocused = textWhenNotFocused;
}

public void setIcon(ImageIcon newIcon){
    this.icon = newIcon;
}

public String getTextWhenNotFocused() {
    return this.textWhenNotFocused;
}

public void setTextWhenNotFocused(String newText) {
    this.textWhenNotFocused = newText;
}

public void paintComponent(Graphics g){
    super.paintComponent(g);

    int textX = 2;

    if(!this.hasFocus() && this.getText().equals("")) {
        int height = this.getHeight();
        Font prev = this.getFont();
        Font italic = prev.deriveFont(Font.ITALIC);
        Color prevColor = g.getColor();
        g.setFont(italic);
        g.setColor(UIManager.getColor("textInactiveText"));
        int h = g.getFontMetrics().getHeight();
        int textBottom = (height - h) / 2 + h - 4;
        int x = this.getInsets().left;
        Graphics2D g2d = (Graphics2D) g;
        RenderingHints hints = g2d.getRenderingHints();
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                             RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.drawString(textWhenNotFocused, x, textBottom);
        g2d.setRenderingHints(hints);
        g.setFont(prev);
        g.setColor(prevColor);
    } else {
        int iconWidth = icon.getIconWidth();
        int iconHeight = icon.getIconHeight();
        int x = dummy.getWidth() + dummyInsets.right;
        textX = x - 420;
        int y = (this.getHeight() - iconHeight)/2;
        icon.paintIcon(this, g, x, y);
    }

    setMargin(new Insets(2, textX, 2, 2));

}
@Override
public void focusGained(FocusEvent arg0) {
    this.repaint();
}

@Override
public void focusLost(FocusEvent arg0) {
    this.repaint();
}

}
And this is where I create the fields;
txtSearchBooks = new JSearchTextField("Buch suchen...");

Now back to my question. Do you have any idea how I can give the image a function where the text will be automatically cleared? I tried to implement a MouseListener and set the text of "txtSearchBooks" to null but it hasn't worked.
I hope I didn't go off in the wrong direction.
Sorry for the long post but I would really appreciate to get some advice.

A: A JTextField is a JComponent, meaning it is also a container for other components. You can use the add(Component c) method to add other components to it. BUT A JTextField won't show its added components unless you provide a LayoutManager to it. Then it behaves just like a normal JPanel.
I made a small example how you can manage what you need. The label is showed to the right, and clicking it will clear the field. You can use a button as well, instead of label.
Please note you don't need to create the Image object from scratch as I do, you can load it from a file. I create it this way so that the example doesn't rely on other files.
public class TextFieldWithLabel {
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField textField = new JTextField("Search...");
        textField.setLayout(new BorderLayout());

        //creating dummy image...
        Image image = new BufferedImage(25, 25, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, 25, 25);
        graphics.setColor(Color.RED);
        graphics.fillRect(2, 11, 21, 3);
        graphics.fillRect(11, 2, 3, 21);

        JLabel label = new JLabel(new ImageIcon(image));
        textField.add(label, BorderLayout.EAST);
        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                textField.setText("");
            }
        });
        frame.add(textField);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}


text:
Q: Switching Iterated Integrals from dxdy to dydx I am having issues switching an iterated integral from dxdy to dydx:

Switch the integral $\int_0^2 \int_y^{2y}6xy$ dx dy to a dy dx  integral in the form of $\int_0^2 \int_{...}^{...}6xydydx$ + $\int_2^4 \int_{...}^{...}6xydydx$

What I'm having issues with here is trying to break it up into pieces-- is the first one just from 0 to y, and the next one from y to 2y?

A: The domain of integration is the inside of the triangle with vertices at the points $(0,0)$, $(2,2)$ and $(4,2)$, bounded by the lines:$y=x$, $y=x/2$ and $y=2$. The integral of an arbitrary function $f(x,y)$ in this domain can be done first in $x$ and then in $y$, or first in $y$ and then in $x$:
$$\int_0^2dy\int_y^{2y}f(x,y)\,dx = \int_0^2dx\int_{x/2}^xf(x,y)\,dy+\int_2^4dx\int_{x/2}^2f(x,y)\,dy$$


text:
Q: Google Fusion Table Query The following javascript code is not working which has a query to google fusion table.
$('#map_canvas').gmap({ 'center': new google.maps.LatLng(37.447038,-122.160575), 'zoom': 11, 'mapTypeId' :  google.maps.MapTypeId.ROADMAP, 'callback': function(map) {

$('#map_canvas').gmap('loadFusion', { 'query': {

    'from': '297050' ,
    'orderBy': ST_DISTANCE('Address', LATLNG(37.447038,-122.160575)),
    'limit':10 } });

var t = setTimeout(function() {$('#dialog').dialog('close');}, 2000);
                }
});

If I remove the query line having the orderby clause (as below) it works fine
$('#map_canvas').gmap({ 'center': new google.maps.LatLng(37.447038,-122.160575), 'zoom': 11, 'mapTypeId' :  google.maps.MapTypeId.ROADMAP, 'callback': function(map) {

$('#map_canvas').gmap('loadFusion', { 'query': {

    'from': '297050' ,

    'limit':10 } });

var t = setTimeout(function() {$('#dialog').dialog('close');}, 2000);
                }
});

Please Advise hot to fix this query

A: The "orderBy" property seems to work as a string.  Instead of:
'from': '297050' ,
'orderBy': ST_DISTANCE('Address', LATLNG(37.447038,-122.160575)),
'limit':10 } });

Try (notice the double quotes (") around the orderBy property:
      query: {
        select: 'Address',
        from: 297050,
        orderBy: "ST_DISTANCE('Address', LATLNG(37.447038,-122.160575))",
        limit:5
      },

Working example


text:
Q: Orchard use ICacheManager to cache authenticated user data I am using Orchard and would like to cache data specific to an authenticated user.
When a new user logs in, or after a period of time, the database should be queried again.
I've accomplished half of this below (after 30 minutes it will query the database again):
private UserData SomeUserSpecificData()
{
    var data = _cacheManager.Get("userdata",
        ctx => {
            ctx.Monitor(_clock.When(TimeSpan.FromMinutes(30)));
            return GetDatabaseData();
        });

    return data;
}

But how would I force the cache to re-query the database when a new user has logged in?
I have a feeling it might involve ISignals but not sure how to implement this.
Thanks.

A: You're absolutely right with ISignals!
You just need to inject ISignals and use it like this:
private readonly Orchard.Caching.ISignals _signals;

private UserData SomeUserSpecificData()
{
  var data = _cacheManager.Get("userdata",
      ctx => {
        ctx.Monitor(_clock.When(TimeSpan.FromMinutes(30)));
        cts.Monitor(_signals.When("SOMETHING_HAPPENED_FOR_xyz"));

        return GetDatabaseData();
      });
  return data;
}

What's also nice to know: You can monitor as many signals as you want.
To keep things clean I'll typically create a static class like this:
public static class CacheSignals
{
  public const string SomethingHappened = "SOMETHING_HAPPENED";
  public const string SomethingHappenedForUser(int userId) => string.Format("SOMETHING_HAPPENED_FOR_{0}", userId);
}

Now you can simply implement a custom EventHandler forOrchard.Users.Events.IUserEventHandler
and invalidate the cache on LoggedIn.
private readonly Orchard.Caching.ISignals _signals;

public void LoggedIn(Security.IUser user)
{
    _signals.Trigger(CacheSignals.SomethingHappenedForUser(user.Id));
}


text:
Q: IdentityServer4 Access Token and Cookies we have a application (Angular 7 front end, .net core micro services and Elastic back end). we are using IdentityServer4 to generate access tokens from the frontend and sending it to the microservices for authorization purpose. the token generation is using user's username/password to validate the user. we have quite download feature in the app to download the pdf files. with the current model we are not able to open a new tab and passing the access token to generate a pdf using one of the microservices. what we understood is if we have a cookie then we can achieve this. so i need help to generate a cookie from Identityserver4 for the UI and Access token for the backend apis.
not able to find any documentation related to get a cookie out of identityserver4. not understanding if the cookie can be used to authorize the apis as well. appreciate your help on this.

A: I think this is quite a common problem in web apps that don't use cookies. One option is to have an API that can return a single-use or time limited (via HMAC + timestamp) URL for the download in question and then navigate the browser to that URL. This avoids having to pass the token in the URL which is best avoided and limits the usefulness of any URL that may get logged and fall into the wrong hands


text:
Q: How to sort a ClientDataSet on a calculated field? I'm trying to sort a ClientDataSet on a calculated boolean field, but for some reason the data is not sorted. I have a boolean field named Highlight with FieldKind set to fkInternalCalc, and an index defined like this:
IndexDefs[0].DescFields = 'Highlight';
IndexDefs[0].Fields = 'Highlight;PatNo';
IndexDefs[0].Name = 'PatNo';
IndexDefs[0].Options = [ixDescending];

and obviously I have set my client dataset's IndexName to 'PatNo'. When I run my application, the data in the CDS is sorted on PatNo field only. Any thoughts?

A: Ime, indexing a ClientDatasSet on a compound index including an fkInternalCalc field works fine.
The code below works in D7 and XE6, and  with Midas.Dll version ten years apart, giving

So, unless there was some kind of regression in XE2, I would suspect the problem reported
was in something at the OP's end.
 // tested with:
//  midas.dll 7.1.1692.668 30 August 2004
//  midas.dll 20.0.16277.1276  16 June 2014

procedure TForm1.SetUp;
var
  Field : TField;
  i : Integer;
begin
  Field := TIntegerField.Create(Self);
  Field.FieldName := 'PatNo';
  Field.FieldKind := fkData;
  Field.Index := 0;
  Field.DataSet := CDS;

  Field := TBooleanField.Create(Self);
  Field.FieldName := 'HighLight';
  Field.FieldKind := fkInternalCalc;
  Field.Index := 1;
  Field.DataSet := CDS;

  CDS.OnCalcFields := CDSCalcFields;

  CDS.CreateDataSet;
  for i := 1 to 10 do begin
    CDS.Insert;
    CDS.FieldByName('PatNo').AsInteger := i;
    CDS.Post;
  end;
end;

procedure TForm1.CDSCalcFields(DataSet: TDataSet);
var
  Value : Integer;
begin
  Value := DataSet.FieldByName('PatNo').AsInteger;
  DataSet.FieldByName('Highlight').AsBoolean := Odd(Value);
end;

const
  scIndexName = 'PatNo';
  scHighlight = 'Highlight';

procedure TForm1.AddHLIndex;
var
  IndexDef : TIndexDef;
begin
  IndexDef := TIndexDef.Create(CDS.IndexDefs, scIndexName, 'Highlight;PatNo', [ixDescending]);
  IndexDef.DescFields := scHighlight;
  CDS.IndexName := scIndexName;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  AddHLIndex;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  SetUp;
end;


text:
Q: How do I make eclipse acknowledge my include files in a C++ Existing Makefile project? Simple question: I have a C++ project configured for a existing makefile and it compiles fine. However, the IDE keeps complaining that it cannot resolve most of my symbols.
How do I configure eclipse to use my includes?

A: Project->properties->C/C++ General->Paths and Symbol
Add the path to your include directory.
You can see in the screenshot, the configuration I use to develop with Qt in C++.

A: I added my includes in the paths and symbols, but they are not added during qt compilation.
For compilation, qt uses these includes and ignores what I've added:
g++ -c -pipe -g -Wall -W -D_REENTRANT -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -Idebug -I. -o debug/bp.o bp.cpp
g++ -c -pipe -g -Wall -W -D_REENTRANT -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -Idebug -I. -o debug/Navigation.o Navigation.cpp
Navigation.cpp:16:22: error: XnOpenNI.h: No such file or directory
Navigation.cpp:17:26: error: XnCppWrapper.h: No such file or directory
Navigation.cpp:18:20: error: XnHash.h: No such file or directory
Navigation.cpp:19:19: error: XnLog.h: No such file or directory
Navigation.cpp:22:16: error: cv.h: No such file or directory
Navigation.cpp:23:18: error: cv.hpp: No such file or directory

I found the answer here:
QT Eclipse Integration - Adding External Libs
It seems that this is a kind of conflict between the CDT and Qt builder, so even if you add the options in CDT as in the screenshot above, the compiler doesn't find them!
You need to add them in the xxx.pro file as this:
http://doc.qt.digia.com/4.5/qmake-variable-reference.html#includepath

A: I had the same problem when I imported an existing Makefile project with:
File -> New -> Makefile Project with Existing Code
If you don't want to configure anything and just want eclipse to recognize all Paths from your existing (working) Makefile on it's own just do the following:

*

*right click on your project -> Clean Project

*right click on your project -> Build Project

The Eclipse Indexer then recognizes all paths on it's own without needing any additional configuration. You just need Eclipse to execute your imported Makefile and everything is resolved (if your Makefile works  properly outside Eclipse).
Tested in:
Eclipse IDE for C/C++ Developers
Version: Luna Service Release 2 (4.4.2)
Build id: 20150219-0600


text:
Q: Check package version at runtime in nodejs? I have some of my entries in package.json defined as "*"
"dependencies": {
    "express": "4.*",
    "passport": "*",
    "body-parser": "*",
    "express-error-handler": "*"
},

I wan't to freeze those values to the current version. How can I know what version my packages are at run time? I don't mind checking one by one since I don't have many of them :)
BTW: I cannot do npm list --depth=0 because I cannot access the vm directly (PaaS restriction), just the logs.

A: You can use the fs module to read the directories in the node_modules directory and then read package.json in each of them.
var fs = require('fs');
var dirs = fs.readdirSync('node_modules');
var data = {};
dirs.forEach(function(dir) {
    try{
    var file = 'node_modules/' + dir + '/package.json';
    var json = require(file);
    var name = json.name;
    var version = json.version;
    data[name] = version;
    }catch(err){}
});
console.debug(data['express']); //= 4.11.2

A: Just in case if you need the version on the front-end, there is an npm package just for this and it can be used both on client-side and server-side.
global-package-version
You can use it in your code like this
import globalPackageVersion from 'global-package-version';

// package name is 'lodash'
globalPackageVersion(require('lodash/package.json'));

// You can type 'packageVersion' in browser console to check lodash version
// => packageVersion = { lodash: '4.7.2'}

packageVersion becomes a global object when used in server side and becomes a window object when used on the client side. Works well with webpack and all other bundling tools.
Disclaimer: I am the author of this package :)

A: I've 'modernised' a bit @laggingreflex answer, this works on ES6+, node 10, tested on a lambda running in aws. It's an endpoint from an express app.

const fs = require("fs");

module.exports.dependencies = async (_req, res) => {
  const dirs = fs.readdirSync("./node_modules");

  const modulesInfo = dirs.reduce((acc, dir) => {
    try {
      const file = `${dir}/package.json`;
      const { name, version } = require(file);
      return { ...acc, [name]: version };
    } catch (err) {}
  }, {});
  res.status(200).json(modulesInfo);
};

A: The accepted solution can be improved upon in both terms of performance and stability:
1: the package name IS THE directory. In typically cases where you are looking for a specific package, you do not need to load every module.
2: this code will not run on all os due to the way the paths are formed
3: using require means the path needs to be relative to the current file (this would only work if your file is located at the top of your project folder & along side node_modules).  In most cases, using readFile or readFileSync is a easier approach.
const fs = require('fs');
const path = require('path');

const dirs = fs.readdirSync('node_modules');
const data = {};
//add ones you care about
const trackedPackages = ['express', 'passport', 'body-parser'];
dirs.forEach(function(dir) {

   if(trackedPackages.indexOf(dir) > -1){
      try{
        const json = JSON.parse(
          fs.readFileSync(path.join('node_modules', dir, 'package.json'), 'utf8')
        );
        data[dir] = json.version;
      }catch(e){
        console.log(`failed to read/parse package.json for ${dir}`, e);
      }
   }

});
console.debug(data['express']); //= 4.11.2


text:
Q: how can i make shorter my Jagged(Ragged ) code? How can i write a shorter code with a for loop, Is it possible? instead of writing;
    int array[][] = new int[10][];
    array[0] = new int[1];
    array[1] = new int[2];
    array[2] = new int[3];
    array[3] = new int[4];
    array[4] = new int[5];
    array[5] = new int[6];
    array[6] = new int[7];
    array[7] = new int[8];
    array[8] = new int[9];
    array[9] = new int[10];

Here is my code;
    int array[][] = new int[10][];
    array[0] = new int[1];
    array[1] = new int[2];
    array[2] = new int[3];
    array[3] = new int[4];
    array[4] = new int[5];
    array[5] = new int[6];
    array[6] = new int[7];
    array[7] = new int[8];
    array[8] = new int[9];
    array[9] = new int[10];

    for (int i = 0; i < 10; i++){
        for (int j = 0; j < i + 1; j++) {
            array[i][j] = i + j;
        }
    }
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < i + 1; j++)
            System.out.printf("%-4d",array[i][j]);
        System.out.println();
    }

}

}

A: For a generic solution, if you decide to change the length of the array
int array[][] = new int[10][];

for (int i = 0; i < array.length; i++) {
    array[i] = new int[i + 1];
}

You could also combine the two loops like
    for (int i = 0; i < array.length; i++) {
        array[i] = new int[i + 1];
        for (int j = 0; j < i + 1; j++) {
            array[i][j] = i + j;
        }
    }

A: You might trying moving the initialization inside the loop
int array[][] = new int[10][];

for (int i = 0; i < 10; i++){
    array[i] = new int[i + 1];
    for (int j = 0; j < i + 1; j++) {
        array[i][j] = i + j;
    }
}
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < i + 1; j++)
        System.out.printf("%-4d",array[i][j]);
    System.out.println();
}

A: how about this?
for (int i = 0; i < 10; i++){
  array[i] = new int[i + 1]
}

or for the mere fun of making it functional (don't ask about other aspects)
//just the empty array
int[][] array = IntStream.range(0, 10)
                         .map(i -> i + 1)
                         .mapToObj(int[]::new)
                         .toArray(int[][]::new);

Or initialize and fill the array in functional style:
//the array with values
int[][] array = IntStream.range(0, 10)
                         .mapToObj(v -> IntStream.range(v, v + v + 1).toArray())
                         .toArray(int[][]::new);

And even do the output this way:
String out = Arrays.stream(array)
                   .map(x -> Arrays.stream(x)
                                   .mapToObj(y -> String.format("%-4d", y))
                                   .collect(Collectors.joining()))
                   .collect(Collectors.joining("\n"));
System.out.println(out);

A: With java 8:
Integer[][] a = new ArrayList<Integer[]>(Collections.nCopies( 10, new Integer[0]  ))
.stream()
.map( p -> new Integer[p.length +1] )
.toArray(size -> new Integer[size][]);

A: code is shorter now thanx :)
    int array[][] = new int[10][];

    for (int i = 0; i < array.length; i++)
    {
        array[i] = new int[i + 1];

        for (int j = 0; j < i + 1; j++)
        {
            array[i][j] = i + j;
        }
    }
    for (int[] row : array)
    {
        for(int k:row)
            System.out.print( k+ " ");
        System.out.println();
    }


text:
Q: Why Android studio is refusing to share project on GitHub? I have an android project in Android Studio which I would like to share on GitHub. Earlier I have shared other projects. But after resetting my PC and installing relevant softwares Android Studio doesn't take my github credentials, so I can't post the project. These are the images respectively.

A: For those who are wondering, I have found the solution. Please follow these steps to solve the issue.
Go to File->Settings (Ctrl+Alt+S).
Then, Version Control->GitHub.
Choose the account. In my case it was showing "Bad credentials" with login option. After providing GitHub password, click OK. Then I followed the original steps as shown in the question. It solved the problem.


text:
Q: merge 2 rows to one on first column I have written following query:
SELECT r.StartTime,
       (CASE d.DayOfWeekendInd WHEN 'Y' THEN COUNT(*) END) as 'WEEKDAY',
       (CASE d.DayOfWeekendInd WHEN 'N' THEN COUNT(*) END) as 'WEEKEND'
FROM t_fact_rit as r
LEFT JOIN  t_dim_date d ON r.DateId=d.DATE_SK
GROUP BY r.StartTime, d.DayOfWeekendInd
ORDER BY r.StartTime;

That results in the following:

How can I join the two time rows so it become one, while still keeping the other two columns?
PS Dialect is MSSQL.

A: You want conditional aggregation.  The CASE expression is the argument to the aggregation functions, not the other way around:
SELECT r.StartTime,
       SUM(CASE WHEN d.DayOfWeekendInd = 'Y' THEN 1 ELSE 0 END) as WEEKDAY,
       SUM(CASE WHEN d.DayOfWeekendInd = 'N' THEN 1 ELSE 0 END) as WEEKEND
FROM t_fact_rit as r LEFT JOIN
     t_dim_date d
      ON r.DateId=d.DATE_SK
GROUP BY r.StartTime
ORDER BY r.StartTime;


text:
Q: How to create a custom user control from another task WITH PARAMETER i just have a strange problem and i didn't get why it happens. Could you please help me to find out why it happens and how i can fix it?
My error is: "The Calling Thread Cannot Access This Object Because A Different Thread Owns It".
My point is that getting some values from databese (it takes a long time therefore i use Task.Run()) and creating custom UI Component with the values and add into a wrap panel.
Firstly, i have an event which is window loaded:
 private async void Window_Loaded(object sender, RoutedEventArgs e)
    {
        await this.ShowAllMatchesAsync(); // This code workfully works
    } // But after right here, it reports an error and doesn't show any code because it is in interrupt mode :(

I have a list which gets value by using async process:
private async Task ShowAllMatchesAsync()
{
      List<Match> allMatches = await new GetValues().GetAllMatchValuesAsync(0); // This workfully works. So, allMatches value has some values which i need it to create UI Using Control:

      // UI_MatchCard is a User Control which i have created
      // This class needs a Match parameter, in this way it automatically creates MatchCard according to match value which i defined as parameter.
      UI_MatchCard matchCard = new UI_MatchCard(allMatches[0]); // I just want to show first match of allMatches for this case.

      // WP_Matches is a Wrap panel. I use it to add UI_MatchCard
      this.WP_Matches.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });
      // It workfully works here. I mean, it adds an UI_Matcherd to WP_Matches (this wrap panel) and count of Wp_Matches equals to 1 after adding it :)
}

When all process is done, it reports an error after processing where i told you (The last line of Windows_Loaded event).
The strange thing is that if I don't add an UI_MatchCard:
this.WP_Matches.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });

And if I add another UI component (like textblock)
this.WP_Matches.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(new TextBlock()); });

It doesn't report anything and workfully works. Also, if i add my UI_MatchCard without any parameter:
  UI_MatchCard matchCard = new UI_MatchCard(); // Without any parameter

  this.WP_Matches.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });

It workfully works again. But as you guess it doesn't show my match values. It just show blank match because i didn't enter the parameter.
Also these are what i have tried:
Changing Invoke methodes:
 this.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });
 Application.Current.Dispatcher.Invoke(() => { this.WP_Matches.Children.Add(matchCard); });

And Task.ContinueWith() method.
How can i find out why it happens? Could you please help me?


text:
Q: jqgrid fluid last column to fit In my jqgrid, I can resize all columns.
Initially when grid is rendered, then all the columns are shrink to fit and there is no empty space at the right edge.
When I resize any column then I always get horizontal scroll (when the column width is increased) or empty space (when column width is decreased). I want to fill this space everytime. i.e. my last column should do that. If any column increased then I would subtract that pixels from last column or if any column is decreased then I would increase that pixels from last column. The result will look like that there is never a horizontal scroll or empty space.
resizeStop: function(width, index) {
    initialWidth = this.p.colModel[3].width; //***see below note about this line***
    var finalWidth = Math.abs(initialWidth - width);
    alert(finalWidth);
}

***this gets me default width at the time of initialisation. I need initial width i.e. before resizing. So that I can do maths with it.
Fiddle - http://jsfiddle.net/aUDHx/597/
Any help greatly appreciated.

A: You need call setGridWidth inside of resizeStop like I suggested in the answer. You should try the code from UPDATED part of the answer if you use one from the latest version of jqGrid. In case if the code do not exactly what you need you should describe the test case and I'll wite how you can fix the problem.


text:
Q: Issues iterating dataframe in pandas I am filling out a dataframe using the content of a list of lists such as:
desc_prep=[['aesthet', 'abod'], [['arb', 'abod'], ['forest', 'abod']]]

col_names =  ['desc_name','desc_avg_vector']
df_desc_prep = pd.DataFrame(columns=col_names)
df_desc_prep['desc_name']=desc_prep

At this point of time I am getting the following:
                         desc_name
0                [aesthet, abod]
1  [[arb, abod], [forest, abod]]

When iterating the dataframe with iteritems to get a tuple with the column name and the content as a Series:
for index, value in df_desc_prep.iteritems():
    print("index: ", index)#-->index:  desc_name
    print("value: ", value)#-->value:  0                  [aesthet, abod]
    print("value[0]:", value[0])#['aesthet', 'abod']
    print("value[1]:", value[1])#[['arb', 'abod'], ['forest', 'abod']]
    if isinstance(value[0], list):#->value[0]:  ['aesthet', 'abod']

When iterating using iterrows() to get a Series for each row:
for index, value in df_desc_prep.iterrows():
    print("index: ", index)#-->index:  0
    print("value: ", value)#-->value:  desc_name    [aesthet, abod]
    if isinstance(value[0], list):#-->value[0]:  ['aesthet', 'abod'], value[1]: IndexError: index out of bounds

I was expecting to get value[0] as aesthet and value[1] as abod. Instead I am getting IndexError: index out of bounds when getting value[1].
How can I get the behaviour of iterating over the dataframe and getting value[0]=aesthet when iterating over ['aesthet', 'abod'] and value[0]=['arb', 'abod'] when iterating over [['arb', 'abod'], ['forest', 'abod']]

A: ...
for index, value in df_desc_prep.iterrows():
    print(value[0][0])
    print(value[0][1])

aesthet
abod
['arb', 'abod']
['forest', 'abod']

for index, value in df_desc_prep.iterrows():
    print(value['desc_name'][0])
    print(value['desc_name'][1])

aesthet
abod
['arb', 'abod']
['forest', 'abod']


text:
Q: Jersey omits XmlTransient annotation during serialization There was a requirment formating java.util.Date into string rather than timestamp in json.
{
    "partyName": "Lifecare Pharmaceuticals",
    "partyShortName": null,
    "lastUpdateDate": 1486639814590, // replace with dd-mm-yyyy hh:mm:ss
}

To achive the date formatting I added the following ObjectMapperProvider
@Provider
@Component
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

   @Override
   public ObjectMapper getContext(Class<?> type) {
      ObjectMapper objectMapper = new ObjectMapper();
      objectMapper.enable(SerializationConfig.Feature.USE_ANNOTATIONS);
      objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
      return objectMapper;
    }
}

The above solution worked but creates another issue ignoring XmlTransient annotation. In model classes Party has collection of PartyContacts and PartyContact mapped like
@Column(name = "PARTY_ID", referencedColumnName = "PARTY_ID", insertable = false, updatable = false)
@ManyToOne(cascade = CascadeType.ALL, optional = false, fetch =FetchType.LAZY)
private Party party;

and getter method
@XmlTransient
public Party getParty() {
    return party;
}

Here the XmlTransient annotation didnt work hence json loading recursively. I've seen  onemore @JsonIgnore annotation but cant make it work with XmlTransient.

A: In Jackson 2.x it can be achieved with a proper AnnotationIntrospector.
Supporting both Jackson and JAXB annotations
To support both Jackson and JAXB annotations, you need a  JacksonAnnotationIntrospector and a JaxbAnnotationIntrospector. Both introspectors can be combined with an AnnotationIntrospectorPair:
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
mapper.setAnnotationIntrospector(pair);

Supporting only JAXB annotations
If you want to support only JAXB annotations, register only the JaxbAnnotationIntrospector:
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.setAnnotationIntrospector(introspector);

Dependency
To use the JaxbAnnotationIntrospector, the following dependency is required:
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-jaxb-annotations</artifactId>
    <version>2.8.6</version>
</dependency>

For more details, have a look at the jackson-module-jaxb-annotations module documentation.


text:
Q: Strip powerpoint presentation of colors (fonts, bullets, number in lists, captions) I have powerpoint files with many many slides that do not meet the accessibility requirements for online teaching. I need to strip the colors off fonts, bullet points, list numbers, and parts of the captions.
what will be helpful is to replace the offending colors with a different color in all of the slides.
The thing is that the file won't let me select all the slides from the slide view panel on the left and make changes to anything. All the menu gets greyed out.
Is there any way to apply changes in color formats to all the slides in a presentation file? I'm using office 2007.
Any tips in accomplishing this is helpful. Thanks in advance.
I've uploaded the offending file here.
https://www.mediafire.com/file/5vf9um4wff4dkv2/shortened_Concepts_of_Biology_Chapter_01.pptx/file

A: The presentation is not based on a theme or any other mechanism
with which one could change all the colors with several clicks.
The colors were modified inside the text manually, not by
applying a theme element, so they need to be changed manually
one by one.
A tool for making the work easier is
Power-user,
a plugin for PowerPoint with a free trial version.
Its Black Friday offer is today at $112.50, but the free trial
version could be enough.
The feature to use is probably "Automate heavy formatting tasks".
If you are into using VBA, the following posts will start you
on the way:

*

*Use VBA to change colors of slide elements in Powerpoint 2013

*PowerPoint VBA - loop all slides, all shapes, find chart, set datalabel color to Black


text:
Q: What is the $hf_mig$ directory for in Windows Server 2003? What is the $hf_mig$ directory for in Windows Server 2003, and can I delete it?

A: Here's a good explanation of the topic: What is the "$hf_mig$" Folder for And Can I Delete It?

A: Its name means "hotfix migration".  It's for tracking versioning information about hotfixes to keep from accidentally breaking or downgrading your system.  No, you definitely should not delete it.


text:
Q: Creating Named Ranges/Tables using cell values I have 300 tables of differing width (different # of columns) and equal length (2 rows).
Next to each table is a single identifying number, say 1 to 300.
I want to know if there is any automatic way to name the "2 x #ofCols" tables using the ID next to each table without selecting the table and manually naming it. Names could be
any suitable format, but require appending the ID to a letter or name, i.e. Table1, Table2... And so on.
Or is there any other handy workaround that anyone can think of?


text:
Q: NSURLRequestCachePolicy.UserProtocolCachPolicy requirements I am using the following code for caching, the response received form the server has the following headers. Is there any header that needs to be set from the request side, for the caching to work for 10 seconds of age.

Connection Received Resopnse Headers= [Date: Sat, 12 Sep 2015 22:51:16
  GMT, Transfer-Encoding: Identity, Server: Apache-Coyote/1.1,
  Content-Type: application/json;charset=UTF-8, Expires: Sat, 12 Sep
  2015 22:51:26 GMT, Cache-Control: max-age=10, must-revalidate]

The mighty code which is not caching.
import UIKit

class HTTPJSONDonwload: NSObject , NSURLConnectionDataDelegate , NSURLConnectionDelegate {
    static let httpjsonDownloader:HTTPJSONDonwload = HTTPJSONDonwload()

    func startDownload(){
        let serverRequest = getServerURL()

        NSURLConnection(request: serverRequest, delegate: self, startImmediately: true)
    }

    func getServerURL() -> NSMutableURLRequest{

        let request:NSMutableURLRequest = NSMutableURLRequest(URL:NSURL(string:"http://citiesfav-jcitiesj.rhcloud.com/Cache/getAllCities")! )
        request.cachePolicy = NSURLRequestCachePolicy.UseProtocolCachePolicy
        request.HTTPMethod = "POST"
        return request
    }

    func connection(connection: NSURLConnection, didReceiveData data: NSData) {

        print("Connection Data= \(NSString(data: data, encoding: NSUTF8StringEncoding))")
    }

    func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
        print("Connection Received Resopnse Headers= \((response as! NSHTTPURLResponse).allHeaderFields)")
    }

    func connection(connection: NSURLConnection, willCacheResponse cachedResponse: NSCachedURLResponse) -> NSCachedURLResponse? {
        print("Connection will cache Response")
        return cachedResponse
    }
}

After removing must-revalidate from the header it was still fetching the request.

Connection Received Resopnse Headers= [Cache-Control: max-age=10,
  Transfer-Encoding: Identity, Date: Sun, 13 Sep 2015 18:35:43 GMT,
  Content-Type: application/json;charset=UTF-8, Server:
  Apache-Coyote/1.1, Expires: Sun, 13 Sep 2015 18:35:53 GMT]

Later findings show the POST request does get cached, but does not work like GET, where max-age is considered.
func startDownload(){
    let serverRequest = getServerURL()
    let cache = NSURLCache.sharedURLCache()
    let response = cache.cachedResponseForRequest(serverRequest)

    if response != nil {
        serverRequest.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataDontLoad
    }

    NSURLConnection(request: serverRequest, delegate: self, startImmediately: true)
}

A: tl;dr
You need to use GET instead of POST.
Lengthy Explanation
The issue is that you're request is a POST.
func getServerURL() -> NSMutableURLRequest{
    ...
    request.HTTPMethod = "POST"
    ...
}

In general, POST requests are used to create (or sometimes also to update) a resource on the server. Reusing the cached response for a creation or update request doesn't make much sense because you have to send the request to the server anyway (otherwise nothing is going to be created or updated). It seems that iOS automatically circumvents the cache on POST requests.
In your particular case, however, you don't really need the POST because you're merely reading data from the server. That means you should use a GET request instead.
func getServerURL() -> NSMutableURLRequest{
    ...
    request.HTTPMethod = "GET"
    ...
}

I verified that the iOS system actually reuses the cache with the following snippet.
let d = HTTPJSONDonwload()

// Initial request. Can not reuse cache.
d.startDownload()

// Subsequent request after 5 seconds. Should be able to reuse the cache.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(5 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
    d.startDownload()
}

// Subsequent request after 11 seconds. Cannot reuse the cache because
// the expiration timeout is 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(11 * NSEC_PER_SEC)), dispatch_get_main_queue()) {
    d.startDownload()
}

When I run this in the simulator and monitor the network calls with Charles Proxy, I indeed only see two events:

The first call is the initial request

and the second call is the third request which was issued after a delay of 11 seconds.

Note that the second request, which was issued after 5 seconds, does not appear which means that the response was retrieved from the cache. The delegate methods of NSURLConnection will, however, still be called just as if the response came from the network. With the logging output in your code you'll, therefore, see all three requests on the console.
Connection Received Resopnse Headers= [Server: Apache-Coyote/1.1, Content-Type: application/json;charset=UTF-8, Keep-Alive: timeout=15, max=100, Proxy-Connection: Keep-alive, Date: Mon, 14 Sep 2015 06:28:05 GMT, Content-Encoding: gzip, Content-Length: 36, Cache-Control: max-age=10, Vary: Accept-Encoding]
Connection Data= Optional({"1":"New York"})
Connection will cache Response
Connection Received Resopnse Headers= [Server: Apache-Coyote/1.1, Content-Type: application/json;charset=UTF-8, Keep-Alive: timeout=15, max=100, Proxy-Connection: Keep-alive, Date: Mon, 14 Sep 2015 06:28:05 GMT, Content-Encoding: gzip, Content-Length: 36, Cache-Control: max-age=10, Vary: Accept-Encoding]
Connection Data= Optional({"1":"New York"})
Connection Received Resopnse Headers= [Server: Apache-Coyote/1.1, Content-Type: application/json;charset=UTF-8, Keep-Alive: timeout=15, max=99, Proxy-Connection: Keep-alive, Date: Mon, 14 Sep 2015 06:28:16 GMT, Content-Encoding: gzip, Content-Length: 36, Cache-Control: max-age=10, Vary: Accept-Encoding]
Connection Data= Optional({"1":"New York"})
Connection will cache Response

Note that there is no Connection will cache Response after the second request because the response was retrieved from the cache and there is no point in caching it again.


text:
Q: Android make home phone When I give number="05338830967"; is like it is working but when I give this number number="03926502323"; it is not running, phone tell me that create internet call what is it?
    private void makePhoneCall(String number) {
      try {

          for (int i = 0; i < number.length(); i++) {
                if ( number.contains("-")) {
                 String[] numaraduzelt = number.split("-");
                 number= numaraduzelt[0]+numaraduzelt[1];
                }
            }
            number="tel:+9"+number;

        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse(number));
                 }
                  }

A: You may want to use the excellent libphonenumber library from Google that is being used everywhere including the Android framework for parsing and formatting phone numbers.  This would allow you to validate the phone number before you attempt to send a dialing Intent.


text:
Q: Dual boot windows 8 and ubuntu 12.04 irst, ubuntu not booting (black screen) I'm trying to dual boot Windows 8 and Ubuntu 12.04 on amy new Asus Zenbook U500VZ with 2x 128 GB ssd in raid0 using Intel Rapid Storage Technology (Windows preloaded).
After a bit of trial and error I finally got Windows working and Grub and Ubuntu installed. But when I chose Ubuntu to boot in Grub I barely see the Ubuntu logo with the dots then I get just a black screen (tried adjusting the screen-brightness as suggested on similar threads) and I hear the drum sounds but then nothing happens.
This is what I did:
I turned off Secure Boot, CSM, Fast Boot and then installed windows in EFI/GPT,  turned off Hibernate in Windows and installed Ubuntu. Since it didn't show the "alongside windows 8" option I tried install it manually in this order after the windows partition.

*

*200mb for grub where I told Ubuntu to place the bootloader

*about 8 GB for swap

*15 GB for '/'

*the rest ~60 GB for '/home'

I then ran Boot Repair and got Grub to load and I have no issue with loading Windows 8.
I don't know what else to do.
Boot-repair gave me this for troubleshooting:
link removed due to link-limtis see link in edit but with /6180438/
EDIT:
Tried reinstalling GRUB2 by following this:
https://help.ubuntu.com/community/Grub2/Installing#via_the_LiveCD_terminal
 but it didn't work:
ubuntu@ubuntu:~$ sudo grub-install --boot-directory=/mnt/boot /dev/mapper/isw_dagfijbabd_RAID0SYS6
/usr/sbin/grub-setup: warn: Attempting to install GRUB to a partitionless disk or to a partition.  This is a BAD idea..
/usr/sbin/grub-setup: warn: Embedding is not possible.  GRUB can only be installed in this setup by using blocklists.  However, blocklists are UNRELIABLE and their use is discouraged..
/usr/sbin/grub-setup: error: will not proceed with blocklists.

now grub won't work either. All i get is a GRUB repair prompt...
EDIT2:
I did a complete reinstall of both OS from scratch. And got windows and grub working again. This time I also get the black screen when trying to load Ubuntu from GRUB but now after a couple of minutes I get this message in a prompt:
Gave up waiting for root device. Common problems:
- Boot args for (cat /proc/cmdline)
  - Check rootdelay= (did the system wait long enough?)
  - Check root= (did the system wait for the right device?)
- Missing modules (cat /proc/modules; ls /dev)
Alert!  /dev/disk/by-uuid/[a hard drive uuid] does not exist. Dropping to a shell!

BusyBox v1.18.5 (Ubuntu 1:1.18.5-1ubuntu4.1) built-in shell (ash)
Enter 'help' for a list of built-in commands.

(initramfs)

Looks like it doesn't load the right partition but why?
Edit 3:
Ran boot-repair again and the black screen is back without the output mentioned above in EDIT2.
Could it be an issue with the NVIDIA GeForce GT 650M? It doesn't show in the system details on the live USB. Is there a way to install drivers from the live USB?
this is the new boot-repair link:
http://paste.ubuntu.com/6184097/
Edit 4:
I tried to install the latest Nvidia driver using
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install nvidia-current-updates

without result....
Edit 5:
Also tried setting the boot line to nomodeset, no splash, nvidia.modeset=0 and GRUB_GFXMODE=1280x1024x32still a black screen with the drumsound.
Edit 6:
If it helps this is my /boot/grub/grub.cfg
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
if [ -s $prefix/grubenv ]; then
  set have_grubenv=true
  load_env
fi
set default="0"
if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}

function recordfail {
  set recordfail=1
  if [ -n "${have_grubenv}" ]; then if [ -z "${boot_once}" ]; then save_env recordfail; fi; fi
}

function load_video {
  insmod efi_gop
  insmod efi_uga
  insmod video_bochs
  insmod video_cirrus
}

insmod part_gpt
insmod ext2
set root='(hd4,gpt7)'
search --no-floppy --fs-uuid --set=root fb4c455f-c123-4c54-abbd-d6217a6c2737
if loadfont /usr/share/grub/unicode.pf2 ; then
  set gfxmode=auto
  load_video
  insmod gfxterm
  insmod part_gpt
  insmod ext2
  set root='(hd4,gpt7)'
  search --no-floppy --fs-uuid --set=root fb4c455f-c123-4c54-abbd-d6217a6c2737
  set locale_dir=($root)/boot/grub/locale
  set lang=en_US
  insmod gettext
fi
terminal_output gfxterm
if [ "${recordfail}" = 1 ]; then
  set timeout=10
else
  set timeout=10
fi
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/05_debian_theme ###
set menu_color_normal=white/black
set menu_color_highlight=black/light-gray
if background_color 44,0,30; then
  clear
fi
### END /etc/grub.d/05_debian_theme ###

### BEGIN /etc/grub.d/10_linux ###
function gfxmode {
    set gfxpayload="${1}"
    if [ "${1}" = "keep" ]; then
        set vt_handoff=vt.handoff=7
    else
        set vt_handoff=
    fi
}
if [ "${recordfail}" != 1 ]; then
  if [ -e ${prefix}/gfxblacklist.txt ]; then
    if hwmatch ${prefix}/gfxblacklist.txt 3; then
      if [ ${match} = 0 ]; then
        set linux_gfx_mode=keep
      else
        set linux_gfx_mode=text
      fi
    else
      set linux_gfx_mode=text
    fi
  else
    set linux_gfx_mode=keep
  fi
else
  set linux_gfx_mode=text
fi
export linux_gfx_mode
if [ "${linux_gfx_mode}" != "text" ]; then load_video; fi
menuentry 'Ubuntu, with Linux 3.8.0-31-generic' --class ubuntu --class gnu-linux --class gnu --class os {
    recordfail
    gfxmode $linux_gfx_mode
    insmod gzio
    insmod part_gpt
    insmod ext2
    set root='(hd4,gpt7)'
    search --no-floppy --fs-uuid --set=root fb4c455f-c123-4c54-abbd-d6217a6c2737
    linux   /boot/vmlinuz-3.8.0-31-generic.efi.signed root=UUID=fb4c455f-c123-4c54-abbd-d6217a6c2737 ro   quiet splash $vt_handoff
    initrd  /boot/initrd.img-3.8.0-31-generic
}
menuentry 'Ubuntu, with Linux 3.8.0-31-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
    recordfail
    insmod gzio
    insmod part_gpt
    insmod ext2
    set root='(hd4,gpt7)'
    search --no-floppy --fs-uuid --set=root fb4c455f-c123-4c54-abbd-d6217a6c2737
    echo    'Loading Linux 3.8.0-31-generic ...'
    linux   /boot/vmlinuz-3.8.0-31-generic.efi.signed root=UUID=fb4c455f-c123-4c54-abbd-d6217a6c2737 ro recovery nomodeset
    echo    'Loading initial ramdisk ...'
    initrd  /boot/initrd.img-3.8.0-31-generic
}
submenu "Previous Linux versions" {
menuentry 'Ubuntu, with Linux 3.8.0-29-generic' --class ubuntu --class gnu-linux --class gnu --class os {
    recordfail
    gfxmode $linux_gfx_mode
    insmod gzio
    insmod part_gpt
    insmod ext2
    set root='(hd4,gpt7)'
    search --no-floppy --fs-uuid --set=root fb4c455f-c123-4c54-abbd-d6217a6c2737
    linux   /boot/vmlinuz-3.8.0-29-generic root=UUID=fb4c455f-c123-4c54-abbd-d6217a6c2737 ro   quiet splash $vt_handoff
    initrd  /boot/initrd.img-3.8.0-29-generic
}
menuentry 'Ubuntu, with Linux 3.8.0-29-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
    recordfail
    insmod gzio
    insmod part_gpt
    insmod ext2
    set root='(hd4,gpt7)'
    search --no-floppy --fs-uuid --set=root fb4c455f-c123-4c54-abbd-d6217a6c2737
    echo    'Loading Linux 3.8.0-29-generic ...'
    linux   /boot/vmlinuz-3.8.0-29-generic root=UUID=fb4c455f-c123-4c54-abbd-d6217a6c2737 ro recovery nomodeset
    echo    'Loading initial ramdisk ...'
    initrd  /boot/initrd.img-3.8.0-29-generic
}
}
### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###

### BEGIN /etc/grub.d/25_custom ###

menuentry "Windows UEFI bkpbootmgfw.efi" {
search --fs-uuid --no-floppy --set=root B6F8-C530
chainloader (${root})/EFI/Microsoft/Boot/bkpbootmgfw.efi
}

menuentry "Windows Boot UEFI loader" {
search --fs-uuid --no-floppy --set=root B6F8-C530
chainloader (${root})/EFI/Boot/bkpbootx64.efi
}
### END /etc/grub.d/25_custom ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/30_uefi-firmware ###
menuentry 'System setup' {
    fwsetup
}
### END /etc/grub.d/30_uefi-firmware ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###

### BEGIN /etc/grub.d/41_custom ###
if [ -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###

and this is my /etc/default/grub
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT=0
#GRUB_HIDDEN_TIMEOUT=0
GRUB_HIDDEN_TIMEOUT_QUIET=true
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
#GRUB_GFXMODE=640x480

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"

EDIT 7
I got ubuntu installed and working. By using the 12.04.03 alternate installer with this modification. [http://]cirrus[.]ucsd[.]edu[/]~pierce[/]fix_ubuntu_usb[/]. Then I booted up and installed updates and nvidia drivers and I'm back to blackscreen! How do I get rid of the nvidia drivers?


text:
Q: Write to outputStream after HTTPServletResponse is committed Is it possible to write response bytes to OutputStream of HTTPServletResponse even if Response is committed?
I have a Servlet Filter which forwards request to CXFServlet by calling doFilter. After doFilter I explicitly want to write bytes in OutputStream. Currently I am not getting response when I write to OutputStream after response is committed.
public void doFilter(ServletRequest servletRequest,
        ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    final ByteArrayPrintWriter pw = new ByteArrayPrintWriter();
    HttpServletResponse wrappedResp = new HttpServletResponseWrapper(
            response) {
        public PrintWriter getWriter() {
            return pw.getWriter();
        }

        public ServletOutputStream getOutputStream() {
            return pw.getStream();
        }
    };
    filterChain.doFilter(servletRequest, wrappedResp);

    byte[] bytes = pw.toByteArray();
    response.getOutputStream().write(bytes);
    response.getOutputStream().flush();
    response.getOutputStream().close();

// Do logging after response is sent to client.

}

A: I see two possible issues:
1) If you receive the content in byte[] bytes from pw (put a breakpoint on that line) that means the filter and wrapper did their job and that your servlet (or other inner filter) did close the real response somehow. Or - try using the Writer instead, I guess ByteArrayPrintWriter does have a method that returns char[] so you can use response.getWriter() to write the content.
2) If there is no content in byte[] bytes then ByteArrayPrintWriter does not collect the content correctly. Note that implementation may (or will) close the response writer, so maybe implementation of ByteArrayPrintWriter closes and thats why you don't get any content.
You can also try the following:
BufferResponseWrapper wrappedResp = new BufferResponseWrapper(response);
filterChain.doFilter(request, wrappedResp);

// get buffered content
char[] chars = wrapper.getBufferContentAsChars();
// modify it somehow
chars = ArraysUtil.join(chars, "peep!".toCharArray());
// flush
wrapper.writeContentToResponse(chars);

from the Jodd project: BufferResponseWrapper.java.
EDIT
Here is the similar filter that worked for me on Tomcat, using just Java classes:
public class MyFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {
}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ByteArrayPrintWriter pw = new ByteArrayPrintWriter(baos);

    HttpServletResponse wrappedResp = new HttpServletResponseWrapper((HttpServletResponse) servletResponse) {
        @Override
        public PrintWriter getWriter() {
            return pw;
        }

        @Override
        public ServletOutputStream getOutputStream() {
            return new ServletOutputStream() {
                @Override
                public void write(int b) {
                    baos.write(b);
                }
            };
        }
    };

    filterChain.doFilter(servletRequest, wrappedResp);
    byte[] bytes = baos.toByteArray();
    servletResponse.getOutputStream().write(bytes);
}

public void destroy() {
}

public static class ByteArrayPrintWriter extends PrintWriter {
    public ByteArrayPrintWriter(OutputStream out) {
        super(out);
    }
}
}

Please note it is a quick-and-dirty implementation, used just for the illustration purposes.


text:
Q: FQL Limit clause showing greater number of results than it should? I have a simple query to show a given users photos:
SELECT pid FROM photo_tag WHERE subject in "12345" LIMIT 400,500

It returns 500 results... shouldn't it return 100?

A: No. Your query is asking for 500 records starting with record 401.
To return the records 400-500 your query should read
SELECT pid FROM photo_tag WHERE subject in "12345" LIMIT 400, 100


text:
Q: Apache2 Vhost attributes I am learning how to create a Virtual Host on my apache2 server, in my *-vhost.conf I have the following  attributes:
ServerName:
ServerAlias
Alias
DocumentRoot -> Points to where the project files are...?
CustomLog -> Points to where my customLog file is..?
ErrorLog -> Points to Apache2 error Log..?
DirectoryIndex:
BrowserMatch:
DeflateFilterNote:
LogFormat:
CustomLog: Decleared 2 times but different path...?
Options:
SetEnv:
SetEnvIfNoCase:

Can someone Explain these in the lamest terms, I did of course google these but I could not find a simple answer....
The Main attributes and their purpose I would like to know about are:
ServerName
ServerAlias
Alias
DocumentRoot

A: You actually need to read some things about Apache Web Server and Virtual Hosts.
You can start from here:

*

*Apache Virtual Host documentation

*Apache Core Features


text:
Q: ValueError at /books/results/ "Field 'id' expected a number but got 'results'."
I'm getting this error while trying to use search filter over a list of books. It was working fine until I changed the Class-based view to Function based view.
This was the Class based view earlier using the default DetailView class:
class BookDetailView(LoginRequiredMixin,DetailView):
    model = models.Book
    template_name='book_detail.html'
    login_url='login'

This is the new Function based detail view I changed to:
@login_required
def book_detail(request,book_id):
    model =models.Book
    book=model.objects.get(id=book_id)
    template ='book_detail.html'
    owner =CustomUser.objects.get(username=book.owner)

    return render(request,template,{'book':book,'owner':owner})

Independently when I'm trying to go to detail view, its working fine. But when I try to search using the 'book_search' view, its throwing this error. Previously search functionality was also working fine.
@login_required
def book_search(request):
    template ='book_list.html'
    model =models.Book
    query =request.GET.get('q')
    results =model.objects.exclude(owner =request.user).order_by('-available','-id')
    if query:
        results =results.filter(Q(title__icontains =query))

    paginator = Paginator(results, 9)
    page =request.GET.get('page')
    try:
        books =paginator.page(page)
    except PageNotAnInteger:
        books =paginator.page(1)
    except EmptyPage:
        books= paginator.page(paginator.num_pages)
    return render(request,template,{'books':books,'query':query,'page':page})

It has something to do with the result set that the search view is returning a list of books while detail view only require just one id.
Edit: Error stack:-
ValueError: invalid literal for int() with base 10: 'results'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\Dell\Documents\read_bus\books\views.py", line 216, in book_detail
    book=results.get(id=book_id)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\query.py", line 404, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\query.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\sql\query.py", line 1337, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\sql\query.py", line 1365, in _add_q
    split_subq=split_subq, simple_col=simple_col,
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\sql\query.py", line 1298, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\sql\query.py", line 1155, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\lookups.py", line 22, in __init__
    self.rhs = self.get_prep_lookup()
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\lookups.py", line 72, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "C:\Users\Dell\.virtualenvs\read_bus-VVRhbVr5\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value
    ) from e

A: For this detail_view:
URLs should look like:
urlpatterns =[
    path('book/<int:pk>',views.book_detail,name ='book_detail'),
    path('results/',views.book_search,name ='search'),
]

While the views function should be this:
@login_required
def book_detail(request,book_id):
    model =models.Book
    book=model.objects.get(id=book_id)
    template ='book_detail.html'
    owner =CustomUser.objects.get(username=book.owner)

    return render(request,template,{'book':book,'owner':owner})

Passing value as http://127.0.0.1:8000/api/book/1

A: I seem to have found the solution.
It was  actually the url pattern for the 'book_detail' that was causing the problem. I had created it without using path converter
urls.py:
...
urlpatterns =[
    path('<book_id>/',views.book_detail,name ='book_detail'),
    path('results/',views.book_search,name ='search'),
]

I thought just using <book_id> would suffice, and since it is higher in the hierarchy
of urlpatterns, it was matched for 'results' too.
Changing the path to <int:book_id> worked. Now I've realised the significance of the little path converter and won't ever forget using this.


text:
Q: In Objective-C is there a way to get a list of the methods called by a method? I have been doing some research online and have found that using the ObjectiveC package in Objective C you can get a list of all the methods on a class using class_copyMethodList(), and I see you can get the implementation (IMP) of a method using instanceMethodForSelector:. The Apple documentation here has been helpful so far but I'm stuck and not sure what I'm really looking to find.
I want a list of the methods/functions called in a given method's implementation so I can build a call tree.
Any suggestions? Thanks in advance!

A: This solution is kind of hard way, and will cause a line of code in every method You can also make use of sqlite and save the tracked methods..

MethodTracker.h

@interface MethodTracker : NSObject

@property (nonatomic) NSMutableArray *methodTrackArr;

+ (MethodTracker *)sharedVariables;

@end

MethodTracker.m

@implementation MethodTracker

static id _instance = nil;

+ (MethodTracker *)sharedVariables
{
    if (!_instance)
        _instance = [[super  allocWithZone:nil] init];

    return _instance;
}

// optional
- (void)addMethod:(NSString *)stringedMethod
{
    // or maybe filter by: -containObject to avoid reoccurance
    [self.methodTrackArr addObject:stringedMethod];
    NSLog("current called methods: %@", methodTrackArr);
}

@end

and using it like:

OtherClass.m

- (void)voidDidLoad
{
    [super viewDidLoad];
    [[MethodTracker sharedVariables] addMethod:[NSString stringWithUTF8String:__FUNCTION__]];
    // or directly
    [[MethodTracker sharedVariables].methodTrackArr addObject:[NSString stringWithUTF8String:__FUNCTION__]];
}
- (void)someOtherMethod
{
    // and you need to add this in every method you have (-_-)..
    [[MethodTracker sharedVariables] addMethod:[NSString stringWithUTF8String:__FUNCTION__]];
}

i suggest you import that MethodTracker.h inside [ProjectName]-Prefix.pch file.
Sorry, for the double answer, i deleted the other one and i have no idea how did that happen..

Hope this have helped you or at least gave you an idea.. Happy coding,
  Cheers!

A: I think in the runtime track method is possible, but function not.
I have been build a tool DaiMethodTracing for trace all methods activity in single class for some of my need. This is based on objective-c method swizzling. So, there is an idea to do this

*

*List all Classes in your application.

*swizze all the methods in each class.

*filter the method you want to trace.

finally, you may got the method call path.


text:
Q: Efficient conversion between vector> and vector> I have a class:
class X {
  vector<shared_ptr<T>> v_;

 public:
  vector<shared_ptr<const T>> getTs() { return v_; }
};

It has a vector of shared_ptr of type T.  For some reason, it needs to expose a method to return this vector.  However, I don't want the content of the vector to be modified, neither are the objects being pointed to.  So I need to return a vector of shared_ptr<const T>.
My question is, is there any efficient way to achieve this?  If I simply return it, it works, but it needs to reconstruct a vector, which is kind of expensive.
Thanks.

A: You can not do that directly - but you can define "views" on your container that let you do something very similar, if you want to make sure that your pointees are const:
boost::any_range<
  std::shared_ptr<const int>,
  boost::random_access_traversal_tag,
  std::shared_ptr<const int>,
  std::ptrdiff_t
> foo(std::vector<std::shared_ptr<int>>& v)
{
  return v;
}

A simple transform iterator adapter / transformed range might do the trick as well, I just used this to illustrate the point.

A: Why not return it as a set of iterators?
class X {
  vector<shared_ptr<T>> v_;
  class const_iterator : std::iterator< std::bidirectional_iterator_tag, T >
  {
    vector<shared_ptr<T>>::iterator it;
    const_iterator( vector<shared_ptr<T>>::iterator& v ) :it (v) { }
    const T& operator*() { return const_cast<const T>( **it ); }
    //forward all methods
  }

   public:
  const_iterator ts_begin() { return const_iterator(v_.begin()); }
  const_iterator ts_end() { return const_iterator(v_.end()); }
};

or something similar? That gives you full control over the type and how it's accessed. Plus you can later change the type w/o changing the api.

A: You are returning by value, so the cost is the same whether you return a copy of the original, vector or a copy of a vector of shared_ptr<T const>: One memory allocation and N atomic increments (approx.).
If what you want to avoid is the creation of the returned vector (i.e. return by value), then it is impossible as different template instantiations are unrelated types no matter how related the arguments to the template are.


text:
Q: Spring error: IllegalStateException: Cannot call sendRedirect() after the response has been committed and getOutputStream() has already been called I have got an error when I try to download a zipped file using Spring boot and spring MVC:
Errors:

*

*SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed] with root cause
  java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

*SEVERE: Servlet.service() for servlet dispatcherServlet threw exception
  java.lang.IllegalStateException: getOutputStream() has already been called for this response

Basically, my app is loading a file, zipping it and download the new zip file.
This is my application Controller:

@Controller
public class ApplicationController {

    public String fileZipped;
    public String inputFile;

    @RequestMapping(method = RequestMethod.GET, value = "/uploadForm")
    public String provideUploadInfo() {
        return "uploadForm";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes,
                                   HttpServletResponse downloadResponse) {
        if (!file.isEmpty()) {
            try {
                inputFile = file.getOriginalFilename();
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(new File(Application.UPLOAD_DIR + "/" + inputFile)));
                FileCopyUtils.copy(file.getInputStream(), stream);
                stream.close();
                redirectAttributes.addFlashAttribute("message",
                        "You successfully uploaded " + file.getOriginalFilename() + "!");
                FileUtils.copyDirectory(Application.UPLOAD_DIR, Application.OUTPUT_FOLDER);
                FileUtils.cleanDirectory(new File(Application.UPLOAD_DIR));
            }
            catch (Exception e) {
                redirectAttributes.addFlashAttribute("message",
                        "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
            }
        }
        else {
            redirectAttributes.addFlashAttribute("message",
                    "You failed to upload " + file.getOriginalFilename() + " because the file was empty");
        }

        return "redirect:/zipFiles";
    }

    @RequestMapping(value = "/download")
    public String handleFileDownload(HttpServletResponse downloadResponse) throws IOException {
        InputStream inputStream = null;
        OutputStream outStream = null;
        try {
            if ( fileZipped!=null && Files.exists(Paths.get(fileZipped))) {
                inputStream = new FileInputStream(fileZipped);
                downloadResponse.setContentType(fileZipped);
                downloadResponse.addHeader("Content-Disposition", "attachment; filename=" + Paths.get(fileZipped).getFileName().toString());
                outStream = downloadResponse.getOutputStream();
                org.apache.commons.io.IOUtils.copy(inputStream, outStream);
                downloadResponse.flushBuffer();
            }
        } catch (IOException e) {
            throw new RuntimeException("IOError writing file to output stream");
        } finally {
            if (inputStream != null) inputStream.close();
            if (outStream != null) outStream.close();
        }
        return "redirect:/uploadForm";
    }

    @RequestMapping(value="/zipFiles")
    public String handleFileZip() throws IOException {
        if(inputFile!=null) {
            fileZipped = zipFiles(Application.OUTPUT_FOLDER, inputFile);
        }
        return "redirect:/download";
    }

    private String zipFiles(String folder, String zipFileName) throws IOException {

        String zipFile =  folder + "/" + FilenameUtils.removeExtension(zipFileName) + ".zip";
        FileOutputStream fileOutputstream = new FileOutputStream(zipFile);
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputstream));

        File []filesArray = new File(folder).listFiles();
        for (File file : filesArray){
            if (!FilenameUtils.getExtension(file.getAbsolutePath()).equals("zip")) {
                byte[] buffer = new byte[1024];
                FileInputStream fileInputStream = new FileInputStream(file);
                zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                int length;
                while ((length = fileInputStream.read()) > 0) {
                    zipOutputStream.write(buffer, 0, length);
                }
                zipOutputStream.closeEntry();
                fileInputStream.close();
            }
        }
        zipOutputStream.close();
        return zipFile;
    }

I do no know why that is happening if I am closing the input and output streams.
Thanks you very much for your help.

A: The problem is with the redirect. Instead of
return "redirect:/uploadForm";

return the view name.
return "/uploadForm";


text:
Q: my drop down menu of nav bar disappear behind the header I should have a drop down menu just like this:

but mine looks like this:

I don't know if is it useful to know that my navbar is a ha-header navbar of tympanus:
http://tympanus.net/Development/HeaderEffects/

.dropdown {
  display: inline-block;
  position: relative;
  z-index: 9999999;
}
.dropdown-content {
  display: none;
  position: absolute;
}
.dropdown-content a {
  display: block;
}
.dropdown-content a:hover,
.dropdown-content a:focus {
  background-image: none;
}
.dropdown-content a:last-child a:hover,
.dropdown-content a:focus {
  background-image: none;
}
.dropdown-content a:first-child a:hover,
.dropdown-content a:focus {
  background-image: none;
}
.dropdown-content a {
  width: 210px;
}
.dropdown:hover .dropdown-content {
  display: block;
}
.parallax-header {
  /* The image used / background-image: url("header.jpg"); / Create the parallax scrolling effect */
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  height: 100vh;
  width: 100%;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  position: relative;
}

  legal solutions

    Link 1
    Link 2
    Link 3

and here is my site if the ispact element helps you:)
www.valaw.gigfa.com

A: I have find out your issue please remove the overflow:hidden in your css
.ha-header-perspective > div {
    backface-visibility: hidden;
    background: #fff none repeat scroll 0 0;
    height: 50%;
    margin: 0 auto;
    overflow: hidden; /* remove this overflow hidden */
    position: relative;
    text-align: justify;
    transition: all 0.5s ease 0s;
    width: 100%;
 }

A: There is a overflow: hidden property setting on .ha-header-front
Insert this in the css file:
.ha-header-front {
   overflow: visible !important;
}


text:
Q: Why is Cake PHP bake creating views containing fields from the wrong table? QUESTION
Why is Cake PHP bake creating views containing fields from the wrong table and how can I get it to use the correct table?
BACKGROUND
I have a cake:
v2.5.1

... and a table:
CREATE TABLE IF NOT EXISTS `user_quotes` (
`id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `message` text COLLATE utf8_general_mysql500_ci NOT NULL,
  `expires` datetime NOT NULL,
  `deleted` tinyint(1) NOT NULL,
  `deleted_date` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `created` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_mysql500_ci COMMENT='UserQuotes' AUTO_INCREMENT=1 ;

... and its model:
class UserQuote extends AppModel
{

}

... and I bake like so (from htdocs/app/):
./Console/cake bake

... and I'm careful to select the UserQuotes controller from the bake menu.
ERROR
The view has the correct title for the UserQuotes table but the included fields and data are from the User model (and users table) instead of from the UserQuotes model (and thus user_quotes table).


text:
Q: tableView doesn't show anything I'm sure my code is withour mistake, because I have two same tableViews and both with same code, same content and same design. But I don't understand why one of my tableViews is shown, and the other one isn't. I'm using Dynamic Prototype Content, Grouped Style and both tableViews are in container view in other ViewController. Here is code:
table.h
#import <UIKit/UIKit.h>

@interface table : UIViewController <UITableViewDataSource, UITableViewDelegate>

{
    NSArray *tabledata;
    NSIndexPath* checkedIndexPath;
}
@property (nonatomic, retain) NSArray *tabledata;
@property (nonatomic, assign) int number;
@property (nonatomic, retain) NSIndexPath* checkedIndexPath;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
+(table*)instance;
@property (nonatomic) NSInteger selectedRow;

@end

table.m
#import "table.h"

@interface table ()

@end

@implementation table
@synthesize tabledata;
@synthesize tableView;
@synthesize checkedIndexPath;
@synthesize number;
+(InstrumentsI*)instance {
    static table *statInst;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        statInst = [[table alloc] init];
    });
    return statInst;
}
@synthesize selectedRow;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    tabledata = [[NSArray alloc] initWithObjects:@"row1", @"row2", @"row3", nil];
    self.selectedRow = 0;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - TableView Data Source methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tabledata count];
}

- (UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    cell = [tableview dequeueReusableCellWithIdentifier:@"identifer"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"identifer"];
    }

    cell.textLabel.text = [tabledata objectAtIndex:indexPath.row];

    if (indexPath.row == self.selectedRow)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

#pragma mark TableView Delegate methods

- (void)tableView:(UITableView *)tableview didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [table instance].selectedRow = indexPath.row;
    if (indexPath.row != self.selectedRow) {
        self.selectedRow = indexPath.row;
    }
    [tableView reloadData];
}

- (void)viewDidUnload {
    [self setTableView:nil];
    [super viewDidUnload];
}
@end

A: Check if you have implemented all the delegates and datasource methods.
Also confirm that you have set your file's owner or controller as delegates and datasource.

A: Try to reload the tableview after loading the data, like:
- (void)viewDidLoad
{
    [super viewDidLoad];
    tabledata = [[NSArray alloc] initWithObjects:@"row1", @"row2", @"row3", nil];
    self.selectedRow = 0;
    [self.tableView reloadData];
}


text:
Q: MutableState value not getting updated in Observer block I have a live data that I am observing in my fragment, in which I have to act on the result received from LiveData and update my MutableState which is used in a composable.
I am not able to figure out why the MutableState value is not getting changed.
Here is how I am doing it:
 viewModel.urlLiveData.observe(
    this@MyFragment as LifecycleOwner
  ) {
    val url = if (!it.isNullOrEmpty()) {
      //perform operations on the string received from live data (it)
    } else if (!someVariable.isNullOrEmpty()) {
      someVariable
      } else null

    url?.let { finalUrl ->
      Log.d("LOG_TAG", "url1: ${finalUrl}")
      urlMutableState.value = UrlMutableState(url = finalUrl)
      Log.d("LOG_TAG", "url2: ${urlMutableState?.value?.url}")

    }
  }

The logcat shows different URLs for url1 and url2 logs. Ideally, it must be same as I am assigning my MutableState a new value.
Here are the logs:
 D/LOG_TAG: url1: javascript:myCallback( )
 D/LOG_TAG: url2: https://someUrl.com/page1

Here, url2 holds the old value of mutableState instead of the new value.


text:
Q: How can the isGenderMatch be compared? I am trying to select the user and compare their gender, since the scheduled appointment with the gynecology specialty cannot be with the user who would be male, since that specialty is only for the female gender. I am comparing them and being a woman I should not get the urlAlert message that I have placed, but even so I still get the UrlAlert
this is the message that comes out according to the condition but it still comes out when the gender is female
@objc func handleConfirmar(){

    guard isGenderMatch == "false" else {

        let alert = UIAlertController(title: "SANNA", message: "Sexo no corresponde a la especialidad.¿Desea ir a la sección mi cuenta para registrar un nuevo familiar?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "NO", style: .default, handler: { action in
        }))
        alert.addAction(UIAlertAction(title: "Sí", style: .default, handler: { action in

            let miCuenta = MiCuentaViewController()
            self.navigationController?.pushViewController(miCuenta, animated: true)

        }))
        self.present(alert, animated: true, completion: nil)

        return
    }

I validate them here
 @objc func reFreshPicker(){

    isGenderMatch = "true"
    isAgeMatch = ""

    print("entro")

    if let especialidad = nombrePicker.pickedElement as? Especialidad{
      let gender = especialidad.getGender()

        let maxAge = especialidad.getMAxAge()
        let minAge = especialidad.getMinAge()

        //guard let mainUsuario = UserDefaults.getUser() else {return}
        //select the user
        let sexo = self.SelectUSerGender

        if(gender == "" || gender == " "){
            isGenderMatch = "false"
        }
        else{
            if(gender != sexo){
                isGenderMatch = "true"

            }else{
                isGenderMatch = "false"
            }

        }

This is my specialty:(Especialidad) class
class Especialidad: PickerType, SearchFilter {
func displayText() -> String {
return especialidad ?? ""
}
func pickerText() -> String {
    return especialidad ?? ""
}

var idEspecialidad: String?
var especialidad: String?

var edadMin: String?
var edadMax: String?
var genero: String?

func getGender() -> String{
    return genero ?? ""
}

func getMinAge() -> String{
    return edadMin ?? ""
}

func getMAxAge() -> String{
    return edadMax ?? ""
}

init(dictionary: [String: Any]){
    self.idEspecialidad = dictionary["idEspecialidad"] as? String
    self.especialidad = dictionary["especialidad"] as? String
    self.edadMin = dictionary["edadMin"] as? String
    self.edadMax = dictionary["edadMax"] as? String
    self.genero = dictionary["genero"] as? String
}

init(idEspecialidad: String?, especialidad: String?) {
    self.idEspecialidad = idEspecialidad
    self.especialidad = especialidad
}

static func all() -> Especialidad{
    return Especialidad(idEspecialidad: "", especialidad: "Todas las Especialidades")
}

static var allNil: Especialidad {
    return Especialidad(idEspecialidad: nil, especialidad: "Todas las Especialidades")
}

}

A: You should use a Bool for isGenderMatch, and you should start the refreshPicker function by setting a false value, not true, otherwise any failure to get data results in you assuming you have a match.
If you set a breakpoint in refreshPicker and step through the code you will see where the problem is. It's hard to say without seeing your data values, but this code looks the wrong way round:
if(gender != sexo) {
    isGenderMatch = "true"
} else {
    isGenderMatch = "false"
}


text:
Q: Emulate landscape iPad orientation in chrome Following code runs iPad emulation in Chrome in portrait orientation.
How can I change it to get landscape orientation?
const {Builder, By, until} = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');

var driver = new Builder()
  .forBrowser('chrome')
  .setChromeOptions(new chrome.Options()
    .setMobileEmulation({deviceName: 'Apple iPad'})
    .addArguments('start-maximized')
  ).build();

PS: Same question in Russian.

A: Mobile Emulation on Chrome Driver doesn't support multiple things. one of them is changing the orientation before starting Chrome or on the Fly. That is why it is recommended not to fully rely on Emulators.
Please check "Differences between mobile emulation and real devices" section in http://chromedriver.chromium.org/mobile-emulation

Testing a mobile website on a desktop using mobile emulation can be
  useful, but testers should be aware that there are many subtle
  differences such as:  entirely different GPU, which may lead to big
  performance changes; mobile UI is not emulated (in particular, the
  hiding url bar affects page height); disambiguation popup (where you
  select one of a few touch targets) is not supported; many hardware
  APIs (for example, orientationchange event) are unavailable.


text:
Q: how can I make sure that control + c don't kill the kernel? I used a YouTube tutorial (https://www.youtube.com/watch?v=asnXWOUKhTA) to create a minimal linux distro, but if I do ctrl + c the kernel crash!
EDIT: I was confused, when I do ctrl + d

A: That is exactly what happens in your linked tutorial starting from the 44:00 point:
The tutorial from 44:00 onwards
The tutorial uses a minimal shell script as /init:
#!/bin/sh
mount -t sysfs sysfs /sys
mount -t proc proc /proc
mount -t devtmpfs udev /dev
sysctl -w kernel.printk="2 4 1 7"
/bin/sh

During the tutorial, a line that adds poweroff -f as the last line of /init was added to the script that creates the initrd file, but the initrd was not actually updated to contain that command.
As PID #1 will be a shell executing the script, and the /bin/sh that displays the root prompt will be its child process, the PID #1 shell will be waiting for /bin/sh to exit, and once it does, PID #1 will exit too. After that, there will be no longer any processes left; and as others have noted in the comments, the loss of PID #1 will make the kernel very unhappy. This will cause a kernel panic, with the message:
Kernel panic - not syncing: Attempted to kill init!

(In this case, it's not so much that init was killed, but that it actually exited on its own. PID #1 is not generally supposed to just exit without either shutting down the system or providing a valid successor for itself.)
There are also other indications that this "minimal Linux distro" is a very rudimentary toy setup. When /bin/sh starts, it says:
/bin/sh: can't access tty; job control turned off

This indicates /bin/sh is not running in a properly set-up console session, and won't be able to react to Ctrl+C or Ctrl+Z keystrokes in the usual way. Instead, on receiving a Ctrl-C, the /bin/sh will just exit like a regular shell command - and after that, the /init script has reached end-of-file and so the shell running the script (as PID #1) will exit too.
Ctrl-D may end up having the same effect, as it is the standard Unix End-Of-File keystroke: normally the TTY driver detects Ctrl-D and converts it into an End-of-File condition, but since the shell here said can't access tty, it might be detecting the Ctrl-D on its own. Basically, the shell will interpret the End-Of-File condition on standard input as "the user got disconnected somehow" and so the shell will exit... causing PID #1 script to reach its end.
To develop this "minimal Linux distro" further, one of the first steps would be to have the /init script replace itself with a process that fulfills the requirements of working as PID #1:

*

*ideally never exiting, but perhaps with ability to exec() a new version of itself to enable updates

*proper initialization of console session and any other configured TTYs (possibly by monitoring that there is always a process associated with those, and starting a getty process for them if it finds the console or a configured TTY without any live processes)

*reaping of orphaned zombies: PID #1 should spend most of its time in wait(-1)ing for SIGCHLD signals from orphaned processes, for which the kernel will assign PID #1 as their PPID. Whenever such an orphaned process dies, the wait() will read its result code, and once that is done, the kernel will be able to clean up the dead process from its process table, so it won't hang around as a zombie.

This might be achieved by adding a suitable configuration for BusyBox /bin/init to the initrd file, and replacing the last line of /init with:
exec /bin/init

The exec here is important: it causes the shell that's currently running the /init script as PID #1 to replace itself with /bin/init, by omitting the fork() system call before exec()ing the new binary. As a result, the PID number will not change, and the /bin/init will be able to assume its role as the true PID #1.


text:
Q: Presenting viewcontroller from modal view giving error I am getting an assertion failure error when debugging my app when trying to go from a modal view to a normal viewcontroller (PBSViewControllerDataDetail.h) (Not the original view controller that presented the modal view)
Essentially what I am trying to do is:
ViewController1, open modal view and do a async request. When it returns to then send the user on to a second, normal view controller which will present the user with the data gained within the modal view.
Everything else works until the modal trys to present the second view controller. I get the error (1st line is my NSLog output from within the method that trys to present the 2nd VC)
2013-09-22 07:24:11.410 PBSDashboard[566:1303] flipToDataView->Send user to PBSViewControllerDataDetail
2013-09-22 07:24:11.411 PBSDashboard[566:1303] *** Assertion failure in -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:], /SourceCache/UIKit_Sim/UIKit-2380.17/UIWindowController.m:211

PLEASE NOTE: I am not using a NavigationViewController within this project and have considered restarting the entire lot and use one but at the moment I am just trying to understand how to go from Modal to normal ViewController that is not the original one.
I have tried cleaning down the targets, recreating the 2nd VC from scratch, both without success.
Code snippets
PBSRequestViewController.h
#import <UIKit/UIKit.h>
#import "Unirest.h"
#import "PBSDaySales.h"

@class PBSRequestViewController;

@protocol PBSRequestViewControllerDelegate
    - (void) requestViewControllerDidFinish:(PBSRequestViewController *)controller;
@end

@interface PBSRequestViewController : UIViewController

@property (weak, nonatomic) IBOutlet id <PBSRequestViewControllerDelegate> delegate;
@property (weak, nonatomic) IBOutlet NSString *calendType;
@property (weak, nonatomic) IBOutlet NSString *targetDate;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;

- (void) runUnirestRequest:(NSString*)urlToGet;
- (void) loadDefaultSettings;
- (NSString*) buildRequestUrl:(NSString*)serverUrl withPort:(NSString*)serverPort withCalenderType:(NSString*)calendarType withDateStringParameter:(NSString*)selectedTargetDate;

- (IBAction)btnBack:(id)sender;

- (PBSDaySales*) deserializeJsonPacket:(NSDictionary*)httpJson;
- (void)createActivityIndicator;
- (void)flipToDataView;

@end

PBSRequestViewController.m (Just the calling function for 2nd vc)
// Method will forward the user on to the data view.
// Used after the uniRestRequest is completed and data exists.
- (void) flipToDataView
{
    NSLog(@"flipToDataView->Send user to PBSViewControllerDataDetail");
    PBSViewControllerDataDetail *dataVc = [[PBSViewControllerDataDetail alloc] initWithNibName:@"PBSViewControllerDataDetail" bundle:nil];

    dataVc.daySalesData = daySalesFigures;

    [self presentViewController:dataVc animated:YES completion: nil];
}

PBSViewControllerDataDetail.h
#import <UIKit/UIKit.h>
#import "PBSDaySales.h"

@interface PBSViewControllerDataDetail : UIViewController
    @property (weak, nonatomic) PBSDaySales *daySalesData;
@end

PBSViewControllerDataDetail.m
#import "PBSViewControllerDataDetail.h"

@interface PBSViewControllerDataDetail ()

@end

@implementation PBSViewControllerDataDetail

@synthesize daySalesData;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSLog(@"View loaded");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

PBSAppDelegate.m
#import "PBSAppDelegate.h"

#import "PBSViewController.h"

@implementation PBSAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        self.viewController = [[PBSViewController alloc] initWithNibName:@"PBSViewController_iPhone" bundle:nil];
    } else {
        self.viewController = [[PBSViewController alloc] initWithNibName:@"PBSViewController_iPad" bundle:nil];
    }
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

A: To go from modal to 'normal' you should be presenting the 'normal' controller behind the modal controller (often in your root nav controller) and then dismissing the modal. Having a nav controller as the root view controller of the window makes life easier because it can be the host of the modal. At no point should you be trying to use a transition from a modal to 'normal', it's always a dismiss of the modal. The modal is on a conceptually different level within the screen layers if that makes sense...