Q: Issue rendering dark mode - ReactJS I'm new and trying a project to make a switch that toggles between two themes;
Here is what I have so far and I'm struggling to understand why it's not toggling between my themes.
theme.js
import { createContext } from "react";

export const themes = {
  dark: "dark-mode",
  light: "white-mode",
};

export const ThemeContext = createContext({
    theme: themes.dark,
  changeTheme: () => {},
});

themeWrapper.js
import React, { useState, useEffect } from 'react';
import { ThemeContext, themes } from './theme.js';
import "./App.css"

export default function ThemeContextWrapper(props) {
  const [theme, setTheme] = useState(themes.dark);

  function changeTheme(theme) {
    setTheme(theme);
  }

  useEffect(() => {
    switch (theme) {
      case themes.light:
        document.body.classList.add('white-mode');
        break;
      case themes.dark:
      default:
        document.body.classList.remove('white-mode');
        break;
    }
  }, [theme]);

  return (
    <ThemeContext.Provider value={{ theme: theme, changeTheme: changeTheme }}>
      {props.children}
    </ThemeContext.Provider>
  );
}

So I've got a wrapper to re-render the app when dark mode is toggled, and two themes that are being exported.
App.css
.white-mode {
  font: #333;
  background: #eee;
  link: cornflowerblue;
}

.dark-mode {
  font: #eee;
  background: rgb(41, 41, 41);
  link: lightblue;
}

Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import ThemeContextWrapper from '.themeWrapper';

ReactDOM.render(
  <ThemeContextWrapper>
    <React.StrictMode>
      <App />
    </React.StrictMode>{' '}
  </ThemeContextWrapper>,
  document.getElementById('root'),
);

So now in App.js I have the button
import './App.css';
import { Button, Container, InputGroup } from 'reactstrap';
import { ThemeContext, themes } from '.theme';
import React from 'react';

function App() {
  const [darkMode, setDarkMode] = React.useState(true);

  return (

Dark/Light mode

        <InputGroup>
          <ThemeContext.Consumer>
            {({ changeTheme }) => (
              <Button
                color="link"
                onClick={() => {
                  setDarkMode(!darkMode);
                  changeTheme(darkMode ? themes.light : themes.dark);
                }}
              >
                Toggle
              </Button>
            )}
          </ThemeContext.Consumer>
        </InputGroup> */}

  );
}

export default App;

But this button doesn't appear to do anything, where have I gone wrong?


Q: TX-row lock contention : Inserting Duplicate values for Unique Key We are getting a TX-row lock contention error while trying to insert data
It happens while running a job which processes an xml with almost 10000 records, inserting the data into a table
We are having a unique key constraint on one of the columns in the table, and in the request we are getting duplicate values. This is causing the locks and thereby the job is taking more time.
We are using hibernate and spring. The DAO method we use is hibernate template's 'save' annotated with Spring Transaction Manager's @Transactional
Any suggestions please?

A: It's not clear whether you're getting locking problems or errors.
"TX-row lock contention" is an event indicating that two sessions are trying to insert the same value into a primary or unique constraint column set -- an error is not raised until the first one commits, then the second one gets the error. So you definitely have multiple sessions inserting rows. If you just had one session then you'd receive the error immediately, with no "TX-row lock contention" event being raised.
Suggestions:

*

*Insert into a temporary table without the constraint, then load to the real table using logic that eliminates the duplicates

*Eliminate the duplicates as part of the read of the XML.

*Use Oracle's error logging syntax -- example here. http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9014.htm#SQLRF55004


Q: eclipse shortcut publish everywhere I would like to change the publish shortcut behaviour to apply to every window i work.
This would remove the need to be in the server view to use this shortcut (CTRL+ALT+P)
So far I followed this post: eclipse key bindings everywhere
Setting "when" to "in windows" did not work. I guess because the shortcut is still part of the category "server"
How can I change the category? Is there another way to fix this?

A: This is not going to work. The command handler for the Publish action (org.eclipse.wst.server.ui.internal.view.servers.ServerActionHandler) expects the current selection to be a server and doesn't do anything if it is not. So you have to be in the server view for it to work.


Q: Rails model design: propose and counter-propose a time I have a model that allows user A to propose a time for an appointment to user B. If B accepts, then event is set. But if B proposes another time, then A must accept or propose another time, and so on. Until one user accept the other's counter-proposal, the appointment won't be set.
How should I model this kind of back and forth proposals and to keep track of current stage in Rails?
Thank you.

A: What you're describing is a state machine.
Older SO question discussing the various gems and plugins of the time, plus some basics.
Newer blog post discussing the hows and whys.


Q: How to serialize canonical/normalized JSON in PHP The order of keys in JSON is not relevant, so PHP's json_encode uses the internal order of keys when serializing JSON format. I'd like to make sure that equivalent JSON is always serialized the same form. For instance $a and $b in the following example
$a = ["foo" => 1, "bar" => 2, "doz" => 3];
$b = ["doz" => 3, "bar" => 2, "foo" => 1];
print json_encode($a)."\n";
print json_encode($b)."\n";

result in different serializations
{"foo":1,"bar":2,"doz":3}
{"doz":3,"bar":2,"foo":1}

but they are equivalent.

A: You need to sort the array in some way, I recommend sorting by key (foo, bar, doz).
http://php.net/manual/en/function.ksort.php
The order will always be the same when using the same keys.
I haven't tested this, but it should work for your code.
$a = ["foo" => 1, "bar" => 2, "doz" => 3];
$b = ["doz" => 3, "bar" => 2, "foo" => 1];
ksort($a);
ksort($b);
print json_encode($a)."\n";
print json_encode($b)."\n";

This will print:

{"bar":2,"doz":3,"foo":1}
{"bar":2,"doz":3,"foo":1}


Q: What directives and other features are available for inputs with a ControlValueAccessor? I have a custom component. It has a ControlValueAccessor injected into it as a provider. This is the generic standard way to make custom components represent form inputs.
For a more precise example the component actually implements ControlValueAccessor and injects itself into itself. This detail should not be important.
I know that this makes the following things available for this component out of the box:

*

*ngModel directive for two-way data binding

*several css-classes managed by Angular: ng-dirty/ng-pristine, ng-valid and ng-touched
Is there any other directives available out of the box besides ngModel? I would expect at least something like blur and change events to work.


Q: I don't know why this is happened and i don't know how to ask this question I'm using termux app, then i try to install npm packages in the different directory in my phone.
The first one "/storage/shared/coding"
.../0/Coding $ npm i node-session
npm WARN deprecated nomnom@1.8.1: Package no longer supported. Contact support@npmjs.com for more info.
npm WARN deprecated @mapbox/geojsonhint@2.0.1: Please make plans to check GeoJSON in some other way
npm ERR! code EPERM
npm ERR! syscall symlink
npm ERR! path ../@mapbox/geojsonhint/bin/geojsonhint
npm ERR! dest /storage/emulated/0/Coding/node_modules/.bin/geojsonhint
npm ERR! errno -1
npm ERR! Error: EPERM: operation not permitted, symlink '../@mapbox/geojsonhint/bin/geojsonhint' -> '/storage/emulated/0/Coding/node_modules/.bin/geojsonhint'
npm ERR!  [Error: EPERM: operation not permitted, symlink '../@mapbox/geojsonhint/bin/geojsonhint' -> '/storage/emulated/0/Coding/node_modules/.bin/geojsonhint'] {
npm ERR!   errno: -1,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'symlink',
npm ERR!   path: '../@mapbox/geojsonhint/bin/geojsonhint',
npm ERR!   dest: '/storage/emulated/0/Coding/node_modules/.bin/geojsonhint'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     /data/data/com.termux/files/home/.npm/_logs/2022-04-25T19_14_38_772Z-debug-0.log
.../0/Coding $  pwd
/storage/emulated/0/Coding

And the second one "/noda"
~/noda $ npm i node-session
npm WARN deprecated nomnom@1.8.1: Package no longer supported. Contact support@npmjs.com for more info.
npm WARN deprecated @mapbox/geojsonhint@2.0.1: Please make plans to check GeoJSON in some other way

added 151 packages, and audited 152 packages in 7s

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

17 vulnerabilities (1 moderate, 12 high, 4 critical)

To address issues that do not require attention, run:
  npm audit fix

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.
~/noda $ pwd
/data/data/com.termux/files/home/noda

Why does node-session can be installed in /noda directory but not in /storage/shared/coding and how can i install it in /storage/shared/coding

A: NodeJs you installed on Termux doesn't have permission to install dependencies on /storage/emulated/0/Coding/node_modules/.bin/geojsonhint.
You can solve it by:

*

*Changing the directory of the project to somewhere with public permissession.

*Running the command with the administration privilege but on Termux, I think.

*Using nvm to install node js instead of default ways.

This problem comes when you try to install node js with Termux. try not to.
NVM repository link: nvm-sh/nvm.
pay attention:

*

*You need to check your dependency tree is compatible with the node version you want to install.

*If the project is big be careful because you can break your project easily.


Q: Numbers from textboxes are add next to each other instead of adding them together I have 3 textboxes in which I write numbers and last one in which is the result. If I write numbers in TextBoxA and TextBoxB instead of adding them together after I press equal button then it put them next to each other.
[]
I tried this code:
 private void EqualsButton_Click(object sender, EventArgs e)
 {
    OutputTextBox.Text = ($"{InputTextBoxA.Text + InputTextBoxB.Text}");
 }

A:
First you must convert text on textbox to int or any number type

Simple way :
    private void EqualsButton2_Click(object sender, EventArgs e)
    {
        int numberA = int.Parse(textBox1.Text.Trim());
        int numberB = int.Parse(textBox2.Text.Trim());

        var result = numberA + numberB;

        textBox3.Text = result.ToString();
    }

Safe way :
    private void EqualsButton_Click(object sender, EventArgs e)
    {
        if (!int.TryParse(textBox1.Text.Trim(), out int numberA))
            numberA = 0;

        if (!int.TryParse(textBox2.Text.Trim(), out int numberB))
            numberB = 0;

        var result = numberA + numberB;

        textBox3.Text = result.ToString();
    }

A: private void EqualsButton_Click(object sender, EventArgs e)
{
  var resultA=0;
  var resultB=0;
  if(!string.IsNullOrEmpty(InputTextBoxA.Text))
        resultA=Convert.ToInt32(InputTextBoxA.Text);
  if(!string.IsNullOrEmpty(InputTextBoxB.Text))
        resultB=Convert.ToInt32(InputTextBoxB.Text);
    OutputTextBox.Text = resultA+ resultB ;
}

A: Don't listen to anyone. Do this
txtResult.Text = string.Empty;

if (!decimal.TryParse(txt1.Text.Trim(), out decimal v1))
{
    MessageBox.Show("Bad value in txt1");
    return;
}
if (!decimal.TryParse(txt2.Text.Trim(), out decimal v2))
{
    MessageBox.Show("Bad value in txt2");
    return;
}

txtResult.Text = (v1 + v2).ToString();

A: You can change into this
 private void EqualsButton_Click(object sender, EventArgs e)
 {
   try
    {
       OutputTextBox.Text = ($"{ Convert.ToInt32(InputTextBoxA.Text.Trim() == "" ? "0" : InputTextBoxA.Text) + Convert.ToInt32(InputTextBoxB.Text.Trim() == "" ? "0" : InputTextBoxB.Text)}");
    }
    catch(exception ex)
    {
      MessageBox.Show("Enter Valid number")'
    }
 }

A: You need to convert text fields to int and after for the answer back to the text.
If you did not enter a value, then there "" is considered as 0 when adding.
private void EqualsButton_Click(object sender, EventArgs e)
{
  OutputTextBox.Text = Convert.ToString(
    Convert.ToInt32(InputTextBoxA.Text == "" ? "0" : InputTextBoxA.Text)
    + Convert.ToInt32(InputTextBoxB.Text == "" ? "0" : InputTextBoxB.Text));
}


Q: Make keyboard NOT dismiss when opening a ModalViewController
Possible Duplicate:
How can I keep the keyboard present even when presenting a modal view controller?

I have an opened keyboard on one viewcontroller and I want to show another one. But when I show it, keyboard goes down. But I don't want it to go down. I want it to stay. How can I achieve this? I don't call any endEditings and resignFirstResponders myself.


Q: Where to get a pre-built Chromium to easily do modifications? Chromium takes too long to get compiled, like 7 hours on a regular powerful desktop. I'm thinking of some where to get a pre-built Chromium, with which I will be able to compile again only some files to re-link to make a new Chromium binary.
Possible to compile just some source code files and re-link (re-link object files)?

A: It's hard to build Chromium from source but it's every easy to build a new browser based on Chromium.
With GitHub Electron, any app based on it is a real Chromium browser, and developers may create custom UI for their Electron-based browsers.
However, modern browsers would require having servers for storing users' sync data, this might not be easily affordable for 1-man development army to create a new browser for the mass.
Electron app is a pack of Chromium sandbox, and Node.js backend, the 2 communicate thru' IPC as Node.js will be able to access all resources.
GitHub Electron:
https://electronjs.org


Q: Pandas: How to pivot rows into columns I am looking for a way to pivot around 600 columns into rows. Here's a sample with only 4 of those columns (good, bad, ok, Horrible):
df:
RecordID   good   bad   ok  Horrible
  A          0      0    1     0
  B          1      0    0     1

desired output:
 RecordID     Column    Value
   A           Good       0
   A            Bad       0
   A            Ok        1
   A          Horrible    0
   B           Good       1
   B            Bad       0
   B            Ok        0
   B          Horrible    1

A: You can use .stack() as follows.  Using .stack() is preferred as it naturally resulted in rows already sorted in the order of RecordID so that you don't need to waste processing time sorting on it again, especially important when you have a large number of columns.
df = df.set_index('RecordID').stack().reset_index().rename(columns={'level_1': 'Column', 0: 'Value'})

Output:
  RecordID    Column  Value
0        A      good      0
1        A       bad      0
2        A        ok      1
3        A  Horrible      0
4        B      good      1
5        B       bad      0
6        B        ok      0
7        B  Horrible      1

A: You can use melt function:
(df.melt(id_vars='RecordID', var_name='Column', value_name='Value')
   .sort_values('RecordID')
   .reset_index(drop=True)
)

Output:
    RecordID      Column    Value
0          A        good        0
1          A         bad        0
2          A          ok        1
3          A    Horrible        0
4          B        good        1
5          B         bad        0
6          B          ok        0
7          B    Horrible        1

A: Adding dataframe:
import pandas as pd
import numpy as np

data2 = {'RecordID': ['a', 'b', 'c'],
        'good': [0, 1, 1],
        'bad': [0, 0, 1],
        'horrible': [0, 1, 1],
        'ok': [1, 0, 0]}

# Convert the dictionary into DataFrame
df = pd.DataFrame(data2)

Melt data:
https://pandas.pydata.org/docs/reference/api/pandas.melt.html
melted = df.melt(id_vars='RecordID', var_name='Column', value_name='Value')
melted

Optionally: Group By - for summ or mean values:
f2 = melted.groupby(['Column']).sum()
df2


Q: How to run kubectl exec on scripts that never end I have a mssql pod that I need to use the sql_exporter to export its metrics.
I was able to set up this whole thing manually fine:

*

*download the binary

*install the package

*run ./sql_exporter on the pod to start listening on port for metrics

I tried to automate this using kubectl exec -it ... and was able to do step 1 and 2. When I try to do step 3 with kubectl exec -it "$mssql_pod_name" -- bash -c ./sql_exporter the script just hangs and I understand as the server is just going to be listening forever, but this stops the rest of my installation scripts.
I0722 21:26:54.299112     435 main.go:52] Starting SQL exporter (version=0.5, branch=master, revision=fc5ed07ee38c5b90bab285392c43edfe32d271c5) (go=go1.11.3, user=root@f24ba5099571, date=20190114-09:24:06)
I0722 21:26:54.299534     435 config.go:18] Loading configuration from sql_exporter.yml
I0722 21:26:54.300102     435 config.go:131] Loaded collector "mssql_standard" from mssql_standard.collector.yml
I0722 21:26:54.300207     435 main.go:67] Listening on :9399
<nothing else, never ends>

Any tips on just silencing this and let it run in the background (I cannot ctrl-c as that will stop the port-listening). Or is there a better way to automate plugin install upon pod deployment? Thank you

A: To answer your question:
This answer should help you. You should (!?) be able to use ./sql_exporter & to run the process in the background (when not using --stdin --tty). If that doesn't work, you can try nohup as described by the same answer.
To recommend a better approach:
Using kubectl exec is not a good way to program a Kubernetes cluster.
kubectl exec is best used for debugging rather than deploying solutions to a cluster.
I assume someone has created a Kubernetes Deployment (or similar) for Microsoft SQL Server. You now want to complement that Deployment with the exporter.
You have options:

*

*Augment the existing Deployment and add the sql_exporter as a sidecar (another container) in the Pod that includes the Microsoft SQL Server container. The exporter accesses the SQL Server via localhost. This is a common pattern when deploying functionality that complements an application (e.g. logging, monitoring)

*Create a new Deployment (or similar) for the sql_exporter and run it as a standalone Service. Configure it scrape one|more Microsoft SQL Server instances.

Both these approaches:

*

*take more work but they're "more Kubernetes" solutions and provide better repeatability|auditability etc.

*require that you create a container for sql_exporter (although I assume the exporter's authors already provide this).


Q: How to put a link on the bottom right hand side of a page I am currently using the following code to do it.

  Load time: 1.1920928955078E-5 seconds

The problem I am having is that if the page is scrollable then it is midway through the page. I am sure that there is a simple solution for this, but I can't come up with it.
Any help or suggestions would be greatly appreciated.

A: You'll need the div have position fixed instead of absolute.
Fiddle: http://jsfiddle.net/hqkm7/

A: <\span style="position: absolute; bottom: 0pt; right: 0pt;">Load time: 1.1920928955078E-5 seconds<\/span>

should be
Load time: 1.1920928955078E-5 seconds

A: you need to use position:fixed instead of position:absolute. position:absolute does not scroll with the page while positions:fixed does (by taking your span out of the flow of the page).


Q: Is this a valid regular language expression for a binary string? Can it be condensed into something more concise? The regular expression is:
(10) U ((10(0 U 1))*10)

The language I am trying to write is this:(q2 is the accept state and {0,1} is the langauge)
(q0,0)=q3
(q0,1)=q1
(q1,0)=q2   — accept state
(q1,1)=q3
(q2,0)=q0
(q2,1)=q0
(q3,0)=q3
(q3,1)=q3


Q: SQL check if next row doesn't exist I have an MsSQL server and what I am doing is selecting rows from the table. Currently I have two rows so I was wondering how would I check if there are no other rows after second one without making another query?
For example
table users
id    name    pass

1     joe     123

2     bob     abc

How would I check if there is no row after 2 with just a query? I am willing to combining it with my current query, which just selects the data.

A: You can return the number of rows in your query as another column:
SELECT id, name, pass, count(*) over () as rows
FROM users

Keep in mind that this is telling you the number of rows returned by the query, not the number of rows in the table. However, if you specify a "TOP n" in your select, the rows column will give you the number of rows that would have been returned if you didn't have "Top n"

A: If you're trying to paginate the trick is to query one more record than you actually need for the current page. By counting the result (mysql_num_rows) and comparing that to your page size, you can then decide if there is a 'next page'.
If you were using mysql you could also use SQL_CALC_FOUND_ROWS() in your query, which calculates the number of rows that would be returned without the LIMIT clause. Maybe there is an equivalent for that in MsSQL?

A: I assume that you are inserting manually the first 2 rows of your table.
According to that, my idea is to just do a select where the id is more than 2 like this:
SELECT * FROM users WHERE id > 2;

I also assume that you are using PHP so mysql_num_rows will return you 0 if no data is found, otherwise it will return you the number of rows from your query and now you know that you need to do a while or some loop to retrieve the data after id number 2.


Q: How to get MouseOver trigger event alter child items I have a MouseOver event for a border.  Within that border (further down) I have a couple of Borders with RotateTransforms... How can I, within the top level Border hover event alter their transform? (i.e. change their rotation?)
<Border.Style>
    <Style>
        <Style.Triggers>
            <Trigger Property="Border.IsMouseOver" Value="True">
                <Setter Property="Border.Background" Value="#f0f0f0" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Border.Style>

Further down the tree, but inside this border is
<Border Padding="3" Width="73" Height="57" Background="White" RenderTransformOrigin="0.5, 0.5">
    <Border.Effect>
        <DropShadowEffect BlurRadius="4" Direction="0" ShadowDepth="0" Color="#aa505050" />
    </Border.Effect>
    <Border.RenderTransform>
         <RotateTransform Angle="-2" />
    </Border.RenderTransform>
</Border>

A: You could use a DataTrigger in an inner border Style with FindAncestor or ElementName binding to get the IsMouseOver of your outer border.
i.e.
<Border.Style>
    <Style TargetType="Border">
        <Setter Property="RenderTransform">
            <Setter.Value>
                <RotateTransform Angle="3"/>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=IsMouseOver}" Value="True">
                <Setter Property="RenderTransform">
                    <Setter.Value>
                        <RotateTransform Angle="6"/>
                    </Setter.Value>
                </Setter>
            </DataTrigger >
        </Style.Triggers>
    </Style>
</Border.Style>


Q: Pass data (retrieved from server) from parent route to its child route My Angular application have parent and child route. I am using (ui-router)
I what to build that parent route data (which are retrieved from server using $resource) are passed to its child route.
Here will be my application code. When I debugged my code, then "phaseTasks" in child route always was empty Array.
flowAdminApp.config(['$stateProvider', '$urlRouterProvider',
  function($stateProvider, $urlRouterProvider){

    $stateProvider
      .state('phase', {
        url: "/phases/:phase_id",
        template: JST['layouts/admin/flows/tasks/index'],
        resolve: {
          phaseTasks: ['$stateParams', 'taskData',
            function( $stateParams, taskData ){
              return taskData.getPhaseTasks($stateParams.phase_id);
          }]
        },
        controller: 'taskListController'
      })
      .state('phase.task', {
        url: "/tasks/:task_id",
        template: JST['layouts/admin/flows/tasks/show'],
        resolve: {
          task: ['$stateParams', 'phaseTasks',
            function( $stateParams, phaseTasks ){

              // phaseTasks is empty Array

          }]
        },
        controller: 'taskController'
      })
}]);

flowAdminApp.factory('taskData', [ '$resource',
  function ($resource) {
    return {
      getPhaseTasks: function (phase_id) {
        return $resource('/admin/tasks.json?phase_id=:phase_id', {phase_id:'@phase_id'}).query({phase_id:phase_id});
      }
    }
}]);

When I changed my code that parent data are static, then "phaseTasks" passed to child route correctly.
flowAdminApp.config(['$stateProvider', '$urlRouterProvider',
  function($stateProvider, $urlRouterProvider){

$stateProvider
  .state('phase', {
    url: "/phases/:phase_id",
    template: JST['layouts/admin/flows/tasks/index'],
    resolve: {
      phaseTasks: ['$stateParams',
        function( $stateParams ){
          return [{a: 1}]
      }]
    },
    controller: 'taskListController'
  })
  .state('phase.task', {
    url: "/tasks/:task_id",
    template: JST['layouts/admin/flows/tasks/show'],
    resolve: {
      task: ['$stateParams', 'phaseTasks',
        function( $stateParams, phaseTasks ){

          // phaseTasks is [{a: 1}]

      }]
    },
    controller: 'taskController'
  })
}]);

How to pass data (retrieved from server) from parent route to its child route or prevent child route loading until parent route data are retrieved from database ?

A: Try to implement your getPhaseTasks service method using a promise
flowAdminApp.factory('taskData', [ '$resource','$q'
  function ($resource,$q) {
    return {
      getPhaseTasks: function (phase_id) {
        var defer = $q.defer();
        $resource('/admin/tasks.json?phase_id=:phase_id', {phase_id:'@phase_id'})
         .query({phase_id:phase_id},
            function(data){
                defer.resolve(data);
             },
            function(error) {
                defer.reject(error);
            });
        return defer.promise;
      }
    }
}]);

I think the problem currently is that the $resource api is async in nature and returns an array, which gets filled in the future. Since there is no promise available for your $state routes the resolve function does not wait.


Q: Xpath selector does not work I'm quite new in XPath and I can't figure out what's wrong with this selector:
'//div[@id="records"].//div[@class="record"]'

The structure html:
The thing is that I want to get all <div class="record"> elements.
What's wrong please?
EDIT: Elaborated snippet:

A: your xpath
wrong syntax, just get rid of the "." and you'll get all the div elements with attribute class="record"
'//div[@id="records"]//div[@class="record"]'

if (as you said in the comments) you want to get all anchor elements then try this xpath:
'//div[@id="records"]/div[@class="record"]/a[contains(@href,"firma")]'


Q: What is the Dojo Equivalent to Button Click In JavaScript -  If I want to fire a button I do this -
<button type = 'button' id='myButton'>HiddenButton</button>

When I want to fire this button click, say, onChange of a text field -
<input type= 'text' onchange ='callAutoClick()'/>

I am not able to do the same in DOJO. I have found a solution using Javascript -
var divId = document.getElementById('myDivID');
divId.getElementsByTagName("button")[0].click();

But I don't want to have the dependency with the DivID. Is it possible to click a button just knowing the button's controlID. All I could find online were methods to define an OnClick() using dojo for a button and not clicking the button itself.
Plus I am designing the page with a BPM Tool so on including sections the DivID changes. When I open the page in FireBug I can see this -

<button class="BPMButton BPMButtonBorder" type="button">Hidden_Cancel</button>

If you guys could suggest me a way to access the DOM object using the data-viewId also it would cater to my need.
Thanks in advance :)

A: You can use dojo/query:

function progClick() {
  require(["dojo/query"], function(query) {
    query("div[data-viewid=myViewId] > button").forEach(function(node) {
      node.click();
    });
  });
}

  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.10.1/dijit/themes/claro/claro.css">

    <button type="button" onclick="alert('my button got clicked!')">My Button</button>

  <button type="button" onclick="progClick()">Programatically Click My button</button>


Q: Expand one card on click Currently using Material-UI-React for the first time to build out cards that expand, the issue I'm running into is when I click on one card to expand, they all expand.How can I refactor my code to only allow the card that is clicked on to expand not affecting the others?

const useStyles = makeStyles(theme => ({
  card: {
    maxWidth: 300
  },
  media: {
    height: 0,
    paddingTop: '56.25%' // 16:9
  },
  expand: {
    transform: 'rotate(0deg)',
    marginLeft: 'auto',
    transition: theme.transitions.create('transform', {
      duration: theme.transitions.duration.shortest
    })
  },
  expandOpen: {
    transform: 'rotate(180deg)'
  }
}));

const HomePageCards = props => {
  console.log(props);
  const classes = useStyles();
  const [expanded, setExpanded] = React.useState(false);

  function handleExpandClick() {
    setExpanded(!expanded);
  }
  return (
    <Card className={classes.card}>
      <CardHeader title={props.title} subheader={`User: ${props.username}`} />
      <CardMedia
        className={classes.media}
        image='https://source.unsplash.com/1600x900/?crafts'
        title={props.title}
      />
      <CardContent>
        <Typography variant='body2' color='textSecondary' component='p'>
          {props.description}
        </Typography>
      </CardContent>
      <CardActions disableSpacing>
        <IconButton
          className={clsx(classes.expand, {
            [classes.expandOpen]: expanded
          })}
          onClick={handleExpandClick}
          aria-expanded={expanded}
          aria-label='show more'
        >
          <ExpandMoreIcon />
        </IconButton>
      </CardActions>
      <Collapse in={expanded} timeout='auto' unmountOnExit>
        <CardContent>
          <Typography paragraph>Method:</Typography>
          <Typography paragraph>
            Step 1:
            {props.step_1}
          </Typography>
          <Typography paragraph>
            Step 2:
            {props.step_2}
          </Typography>
          <Typography paragraph>
            Step 3:
            {props.step_3}
          </Typography>
          <Typography>
            Step 4:
            {props.step_4}
          </Typography>
          <Typography>
            Step 5:
            {props.step_5}
          </Typography>
        </CardContent>
      </Collapse>
    </Card>
  );
};

import React, { useEffect, useState } from 'react';
import Axios from 'axios';

import HomePageCards from '../HomePageCards/HomePageCards';

const HomePage = props => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const token = localStorage.getItem('token');
    Axios.get('https://bw-how-to.herokuapp.com/guides', {
      headers: { authorization: token }
    })
      .then(res => {
        // console.log('Data', res.data);
        setUsers(res.data);
      })
      .catch(err => console.error(err));
  }, []);

  return (

      {users.map(user => (
        <HomePageCards {...user} key={user.id} />
      ))}

  );
};

export default HomePage;

I looked around but can't seem to find the solution. Any suggestions or guidance would be greatly appreciated. Thank you in advance.


Q: Contact Form 7 allow in HTML tag area How can I enable contact form 7 shortcode in HTML area( Where only allow html tag ) .
[contact-form-7 id="2358" title="Contact Form 1"]
Actually, I would like to allow 3rd slide of my web site.
http://vistabrand.com/

A: You can output it in php like this
<?php echo do_shortcode( '[contact-form-7 id="617" title="capta contact form"]' ); ?>

Search on web little bit before posting, Search on web little bit before posting,
 I found this on Google.


Q: Can I control visibility of generated protobuf-classes in Java? I found an answer for .NET, but can't find a way for Java. I'd like to set the visibility of the generated protobuf-classes automatically to private.
Currently, when I compile my .proto-Files, everything is set to public.


Q: Only a part of data ca be inserted into csv I want to insert all data which I scrape from web into csv, but only a part of info can be inserted!
why this happen
should I use MySQL database instead of csv
And I want to connect this csv file to web browser by using flask.
plus when I insert many import text like "import re" into top of the function "input_to_output(site,oc,id,place,pg)" after "import csv" , I can not import most of them. Is this because csv method do something?
The most thing I want to know is the first one why only a part of data can be inserted.
def townwork_page(oc,place,pg):
    import csv
    import re
    from bs4 import BeautifulSoup
    import requests
    name_list=[]
    ac={"":"","北海道":"101","青森":"110","東京":"041","茨城":"047","千葉":"043","埼玉":"044","群馬":"045","神奈川":"042","栃木":"046",\
    "秋田":"110","岩手":"109","山形":"108","宮城":"106","福島":"107","静岡":"600","愛知":"081","岐阜":"085","山梨":"118","新潟":"117","福井":"124",\
    "長野":"116","滋賀":"064","富山":"122","石川":"123","三重":"084","奈良":"065","和歌山":"066","京都":"063","大阪":"061","兵庫":"062","鳥取":"133",\
    "島根":"134","岡山":"132","佐賀":"441","山口":"135","広島":"131","香川":"136","徳島":"138","愛媛":"137","高知":"139","福岡":"440","長崎":"442",\
    "大分":"444","熊本":"443","宮崎":"445","鹿児島":"446","沖縄":"447"}
    jc={"":"","IT/コンピュータ":"005","営業":"009","専門職/その他":"017","レジャー/エンタメ":"011","接客/サービス":"010","物流/配送":"012","建築/土木":"013","教育":"014"\
    ,"医療/介護/福祉":"015","飲食/フード":"001","販売":"002","事務":"003","総務/企画":"004","IT/コンピュータ":"005","軽作業":"018","芸能":"008","マスコミ/出版":"007",\
    "工場/製造":"019"}
    if any([oc not in jc, place not in ac]):
        print("Input collectlly!")
        return ""
    if type(oc)==str:
        oc=oc,""
    if type(place)==str:
        place=place,""
    url_form="https://townwork.net/joSrchRsltList/?"
    if oc:
        for i in oc:
            if i:
                url_form+="jc="+jc[i]+"&"
    if place:
        for j in place:
            if j:
                url_form+="ac="+ac[j]+"&"
    if pg:
        for l in range(1,pg+1):
            url_form+="pg="+str(l)+"&"
            if url_form[-1]=="&":
                url_form=url_form[:-1]
                res=requests.get(url_form)
                soup=BeautifulSoup(res.text,"html.parser")
                company_name=soup.findAll(class_="job-lst-main-ttl-txt")
                for i in company_name:
                    if i.get_text().split() not in name_list:
                        name_list.append(i.get_text().split())
    return name_list
def input_to_output(site,oc,id,place,pg):
    import csv
    if site=="タウンワーク":
        with open ("output.csv","w+",newline='',encoding="utf-8") as csvFile:
            try:
                writer=csv.writer(csvFile,lineterminator='\n')
                writer.writerow(["information"])
                for line in townwork_page(oc,place,pg):
                    writer.writerow(line)
            finally:
                csvFile.close()
    elif site=="食べログ":
        with open ("output.csv","w+",newline='') as csvFile:
            try:
                writer=csv.writer(csvFile)
                writer.writerow(("information"))
                writer.writerow((tabelog_page(place,pg)))
            finally:
                csvFile.close()
    else:
        print("write collectlly!")

input_to_output("タウンワーク","営業","","北海道",10)

scraping site is "タウンワーク".
Is there any grammer problem


Q: How to implement Google's DoubleClick Ads in an android application? How do we implement google's double click for displaying ads in our android application?
Can someone provide me steps that needs to be followed to implement the same.
Thanks in advance

A: Check this link -  http://code.google.com/mobile/afma_ads/docs/ it explains it all (well most of it to get started!)

I went on a similar path looking for a ad serving support in my android app - eventually I settled for Mobclix - I am happy :-)  Check the question I had posed at  Serving Ads in Android App -


Q: Chrome Packaged App: Open Website in New Tab I'm updating one of my chrome apps to just launch the web app (why? I don't have the time to continue updating the chrome app, alone with the desktop apps for offline use)
Here's what the manifests starts with...
"app": {
   "background": {
      "scripts": [ "background.js" ]
   }
},

I just want it to open a new tab to the website now instead of launching a packaged app. So I tried the following...
"app": {
   "launch": {
      "web_url": "http://stackoverflow.com/"
   }
},

An error occurred: Failed to process your item.
Please specify background subsection of app section in the manifest.
"app": {
   "launch": {
      "web_url": "http://stackoverflow.com/"
   },
   "background": {
      "scripts": [ "background.js" ]
   }
},

An error occurred: Failed to process your item.
Application specifications for packaged and hosted apps are incompatible. Please refer to manifest specification.
The manifest may not contain a launch object inside the app object.
So I decided to stick with just the background script and try to just create a new tab that way.
background.js
chrome.app.runtime.onLaunched.addListener(function(launchData) {
  chrome.app.window.create(
    'index.html',
    {
      id: 'mainWindow',
      innerBounds: {
        'width': 800,
        'height': 600
      }
    }
  );
});

index.html
<script>
  var a    = document.createElement("a")
  a.href   = "http://stackoverflow.com/"
  a.target = "_blank"
  document.body.appendChild(a)
  a.click()
</script>

I was finally able to successfully add a new tab with...
chrome.app.runtime.onLaunched.addListener(function(launchData) {
  window.open("http://stackoverflow.com/")
})

in my background.js script.
However the following error occurs...

I clicked on the "Learn More" button but that too gave me the same "Aw, Snap!" page
Does anyone know why I can't open a new tab in a chrome packaged app?
and
How am I suppose to open a new tab in a chrome packaged app?

A: Use chrome.browser.openTab({ url: "" }, callback) with the "browser" permission.
https://developer.chrome.com/apps/browser#method-openTab


Q: Other Users Cannot Connect to SQL Data Connection I have been banging my head for hours now trying to figure out this issue.  Currently, I have an Excel 2013 file that I created with a few pivot charts.  The pivot charts are connected to SQL Server 2012.  I personally can refresh the data without any issues on my end, however whenever someone else tries to
open the database connection they receive the following error.  I have tested this on multiple users and each one experiences the same error.  Any suggestions on what's going on here?

A: Either your users need to instal the same SQL Server driver you use, or you need to change yours to match their drivers:
https://support.microsoft.com/en-us/help/2022518/error-message-class-not-registered-when-you-update-powerpivot-data


Q: objective c setter method memory management I have question about allocating and releasing objects:
if I have code like this:
MyObject *object = [[MyObject alloc] init];
NSMutableString *string = [[NSMutableString alloc]initWithString:@"bla"];
object.myString = string;
NSLog(@"retain count: %d",[object.myString retainCount]); //gives me 2
[string release];
NSLog(@"retain count: %d",[object.myString retainCount]); //gives me 1

Than I have exactly what I want. I need just one reference and I have retain count 1
but
if I use
object.myString = [[NSMutableString alloc]initWithString:@"bla"];

my property look like this:
@property (nonatomic,retain) NSMutableString *myString;

one alloc, and one setter method with retain gives me as retain count 2
If I release the object after resignment than the app crashes. I dont know why?
So , do i have to always create an object with a temporary reference, than assign to real reference and release the temp reference like first code?
or is there any other way?

A: Yes and no.  Generally, this is a common pattern:
// create the object, retain count 1
MyObject *myObject = [[MyObject alloc] init];

// increment the retain count in the setter
self.myObjectProperty = myObject;

// let go of the object before the end of the current method
[myObject release];

You can avoid the release, sort of, by using autorelease pools.  More accurately, you indicate that you want the object to be released soon:
MyObject *myObject = [[[MyObject alloc] init] autorelease];
self.myObjectProperty = myObject;

// all done!

With many of the Apple-provided classes, you can use class methods other than alloc/init to get objects that are already autoreleased.  Your example could be rewritten as:
MyObject *myObject = [[MyObject alloc] init];
myObject.myString = [NSMutableString stringWithFormat:@"bla"];

A final note: -retainCount is a blunt object.  Particularly with NSStrings and other built-in classes, it may return results that are quite different from what you expect.  Generally you should avoid it.


Q: C# anonymous method/block? I cannot understand this piece of code what is the "ViewDissapearing"? And what about "add" and "remove" blocks?
public event EventHandler ViewDisappearing;

public event EventHandler ViewDissapearing {
    add {
        ViewDisappearing += value;
    }
    remove {
        ViewDisappearing -= value;
    }
}

A: This is done to provide two names for the same event. "ViewDissapearing" is how the event was previously wrongly named, and all existing code that subscribes to the "ViewDissapearing" event is instead rerouted to subscribe to the new correctly spelt "ViewDisappearing" event instead.
The add { ... } block is executed when someone calls ViewDissapearing += ..., which does nothing more than ViewDisappearing += that same .... Similarly for the remove { ... } block and -=.

A: This is to allow other code to attach to this event. This is the same idea as the Get / Set Property of a variable. For Events it is Add / Remove. As with Properties of variables, you can use the Variable directly, or you can use an Property. You usually use the Properrty if you want to add some custom code when adding a event.

A: This is explicitly stating what is normally autogenerated by the compiler for an event in a class.


Q: How do I convert quaternion values to specific angles I'm getting quaternion values, and I want to convert these values to 2 angles.
One of the angles is between the "ground plane" (please correct me if this is an incorrect name for it) and the fictional vector between the origin and the quaternion point ( the complementary angle of gamma ).
The second angle is the rotational angle, this is the rotation that the vector has made relatively to a plane perpendicular to the vector ( R in the picture ).
I looked lot up on the internet, but everything I try has a range of -90° to 90°, while I want it to go from -180° to 180°.
This is the last version of code I ended up with:
float gx = 2 * (x*z - w*y);
float gy = 2 * (w*x + y*z);
float gz = w*w - x*x - y*y + z*z;
float yaw = atan2(2*x*y - 2*w*z, 2*w*w + 2*x*x - 1); // about Z axis
float pitch = atan(gx / sqrt(gy*gy + gz*gz)); // about Y axis
float roll = atan(gy/gz); // about X axis

Serial.print("  yaw ");
Serial.print(yaw * 180/M_PI,0);
Serial.print("  pitch ");
Serial.print(pitch * 180/M_PI,2);
Serial.print("  sideways ");
// Don't mind this section as I'm applying a mathematical function I created
if(pitch > 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,((pitch * 180/M_PI)-51.57)))), 2);
else if(pitch == 0) Serial.println(roll * 180/M_PI, 2);
else if(pitch < 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,(((pitch) * (-180)/M_PI)-51.57)))), 2);

A:
You should always use atan2(y,x) instead of atan(y/x). It is a common mistake. – Somos

He wrote this on a math form were I asked this too, and that was my stupid mistake -_-
My new version is:
float gx = 2 * (x*z - w*y);
float gy = 2 * (w*x + y*z);
float gz = w*w - x*x - y*y + z*z;
float yaw = atan2(2*x*y - 2*w*z, 2*w*w + 2*x*x - 1); // about Z axis
float pitch = atan2(gx, sqrt(gy*gy + gz*gz)); // about Y axis
float roll = atan2(gy, gz); // about X axis

/*Serial.print("  yaw ");
Serial.print(yaw * 180/M_PI,0);*/
Serial.print("  pitch ");
Serial.print(pitch * 180/M_PI,2);
Serial.print("  sideways ");
// Please don't pay  attention to the extra function I made for the project but it doesn't have to do with the problem
if(pitch > 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,((pitch * 180/M_PI)-51.57)))), 2);
else if(pitch == 0) Serial.println(roll * 180/M_PI, 2);
else if(pitch < 0) Serial.println((roll * 180/M_PI) * (1/(1+pow(1.293,(((pitch) * (-180)/M_PI)-51.57)))), 2);


Q: Navigation based application without a uitableview error I do this:
First create navigation based application.
Then delete UITableView from rootViewController.xib, add a UIView connect it to File's Owner.
Change UITableView to UIViewController in RootViewcontroller.h
Finally clean all methods of UITableView in RootViewcontroller.m
But when I run the project receives this error:
-[RootViewcontroller tableView:numberOfRowsInSection:]:unreconized selector sent to instance

What am I doing wrong?

A: There are a few possibility.

*

*Make sure that UITableView protocol is implemented in the header file.
Eg @interface TestingViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

*Check that your connection from in the Interface Builder and make sure its linked properly


Q: Datepicker Javafx I am facing difficulty in date picker implementation (JAVAFX). I need these characters in my date picker I want to restrict only numeric input and a specific length of input in the date picker.It should have fixed / / in it which cannot be removed by user.


Q: Android: best way(9 patch or gradient shape in xml) to draw two gradients(see screenshot)
I need to add background to a textview, the background has two parts: top half is a gradent from color A to B, bottom part is a gradient from color C to D and B does not equal to C, it is actually a semi-transparent shadow, I intentionally put an orange layer underneath it to make it clear to see.
I am looking for the best way to do it, using shape/gradient only allows me setting startColor, centerColor and endColor but I need for color points. Using 9 patch is a bit complicated. Or can I merge two gradients together so each has two colors and together give me four colors?
Thanks!

A: 9 patch seems the simplest way to achieve what you want. And I believe, it would generate less computations to display your image.
9 patch is not so complicated, even easy. Did you try the android 9 patch tool?


Q: yii active record join models Using Yii framework.
I have 3 models.
Articles - table articles(id, name)
ArticlesToAuthors - table articles_to_authors (id, article_id, author_id, type)
Authors - table authors (id, name)
I need to get authors.*, article_to_authors.type for specific article_id.
I was trying to make relation in ArticlesToAuthors model like that:
'authors'  => array(self::HAS_MANY, 'Authors', array('id' => 'author_id'), ),

then i made query:
$authors = ArticlesToAuthors::model()->with('authors')->findAll(array('condition' => 'article_id=2217') );

foreach($authors as $a)
{
     //this is not working
     #var_dump($a->authors->name);
         #var_dump($a->name);

     //this works fine
     foreach($a->authors as $aa)
     {
            var_dump($aa->name);
     }
}

*

*Can i get all active record object in one and not to do foreach in foreach?
I need an analogue to sql "SELECT atoa., a. FROM articles_to_authors atoa LEFT JOIN authors a ON atoa.author_id=a.id WHERE atoa.article_id=:article_id"

*Am i doing right?
p.s. - sorry for my bad english.

A: It looks like you need the following relations:
in your ArticlesToAuthors table:
'author' => array(self::BELONGS_TO, 'Authors', 'author_id'),
'article' => array(self::BELONGS_TO, 'Articles', 'article_id'),

and, for completeness, in your Authors table:
'articlesToAuthors'  => array(self::HAS_MANY, 'ArticlesToAuthors', array('id' => 'author_id'), ),

This should allow you to access $a->author->name. Not tested, that's just off the top of my head.


Q: Pyqt add 9 elements in layout and then lot of layout in group box I want to make elements in row in one layout and a lot of layouts will be in GroupBox, it must  be like this.
Result Interface
I try to release this
formLayout = QFormLayout()

for i in range(50):
    formLayout.addRow(QLabel(i), QPushButton("Start"))

groupBox.setLayout(formLayout)
self.scrollArea.setWidget(groupBox)
self.scrollArea.setWidgetResizable(True)

Result from code
I know that i should make in grib layout, because i have a lot of elements, but how can I create a layout with layouts which everyone have 9 elements?
Just explain how it should be grouped , like this scrollArea->groupBox->formLayout.addrow(elements)
I don't need full code, him I can write myself.

A: The layout you're showing is not a form layout, it could be a grid layout, but it actually seems more like a QTableView (or QTableWidget) or even a QTreeView (if those small arrows on the left are used to expand elements). Using nested layouts in this case might not be a good solution, as each layout would be independent from the others, with the result that the widgets might not be properly aligned. This small arrows for expand element in that case a QTreeView with a QStandardItemModel or a QTreeWidget might help, then use setItemWidget() to add buttons. –
musicamante


Q: Header android 9patch I would like to create a full screen header for Android.
I created the image that is 70 * 480 px (& 9patch).
how can I do?
I tried using the galaxy tab .. but it does not fill the screen horizontally.
This is the code:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:foo="http://schemas.android.com/apk/res/aaa.bbb"
    android:id="@+id/db1_root"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background">
 <ImageView
                android:src="@drawable/header"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="top"
                    >
</ImageView>

thanks in advance.

A: You need to set the android:scaleType and optionally android:adjustViewBounds.  Play around with these two attributes to get the desired effect.
http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType

A: Use this code to add your ImageView to the xml file
            <shush.android.util.AspectImageView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/header" />

Add this class:
package shush.android.util;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author Sherif elKhatib
 *
 */
public class AspectImageView extends View {

    public AspectImageView(Context context) {
        super(context);
    }

    public AspectImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AspectImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = width * getBackground().getIntrinsicHeight()
                / getBackground().getIntrinsicWidth();
        setMeasuredDimension(width, height);
    }
}

A: try this
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/aaa.bbb"
android:id="@+id/db1_root"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background">
<ImageView
            android:src="@drawable/header"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="top"
                >
</ImageView>


Q: How to add picture to JLabel? How to add a picture to JLabelin Java?

A: You can use ImageIcon
JLabel l = new JLabel(new ImageIcon("path-to-file"));

A: Try this code:
ImageIcon imageIcon = new ImageIcon("yourFilepth");
JLabel label = new JLabel(imageIcon);

For more Info

A: jLabel1 = new javax.swing.JLabel();
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\admin\\Desktop\\Picture 34029.jpg"));

Here i posted the code that got generated automatically in netbeans.Hope my code helps in this regards keep coding goodluck.

A: You have to supply to the JLabel an Icon implementation (i.e ImageIcon). You can do it trough the setIcon method, as in your question, or through the JLabel constructor:
Image image=GenerateImage.toImage(true);  //this generates an image file
ImageIcon icon = new ImageIcon(image);
JLabel thumb = new JLabel();
thumb.setIcon(icon);

I recommend you to read the Javadoc for JLabel, Icon, and ImageIcon. Also, you can check the How to Use Labels Tutorial, for more information.
Also have a look at this tutorial: Handling Images in a Java GUI Application


Q: PowerShell: Difference between (ConvertTo-* | Set-Content) and (Export-*)? I'm new to PowerShell, and trying to learn things the write way, I noticed in this case that I can export data in many different manners, what I want to ask about is this case,
Get-Process | ConvertTo-Csv | Set-Content -Path .\Process.txt

and :
 Get-Process | Export-Csv -Path .\Process.txt

Both exports the list of the processes into a CSV file on my desktop, and give the same result.
The first one :
Converts the processes to CSV first then it writes it onto the file.
The second one :
Exports the Processes directly to the file.
What's really the difference between the two cases, is there performance difference, time execution difference, or anything else I'm not aware of ?

A: They are pretty much the same. There shouldn't be any big difference when it comes to performance and time:
Measure-Command { Get-Process | ConvertTo-Csv | Set-Content -Path .\Process.txt }

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 2
Milliseconds      : 880
Ticks             : 28801761
TotalDays         : 3,33353715277778E-05
TotalHours        : 0,000800048916666667
TotalMinutes      : 0,048002935
TotalSeconds      : 2,8801761
TotalMilliseconds : 2880,1761

Measure-Command { Get-Process | Export-Csv -Path .\Process2.txt }

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 2
Milliseconds      : 772
Ticks             : 27724661
TotalDays         : 3,20887280092593E-05
TotalHours        : 0,000770129472222222
TotalMinutes      : 0,0462077683333333
TotalSeconds      : 2,7724661
TotalMilliseconds : 2772,4661

This is because Export-CSV and ConvertTo-CSV run 90% of the same code. They share the same helper-class Microsoft.PowerShell.Commands.ExportCsvHelper to create the header and convert objects to csv. The only difference is that ConvertTo-CSV writes the CSV-object(string) to the pipeline using WriteObject(), while Export-CSV directly writes it to a file using a StreamWriter.
To find this yourself, you could look inside Microsoft.PowerShell.Commands.Utility.dll. I won't be posting the code directly because I'm not sure if it's legal or not. :-)
If you need the CSV-output to be displayed or sent through a third-party API etc., then use ConvertTo-CSV. If you need the data stored in a CSV-file, then you should use Export-CSV.


Q: How to test mp3 upload in Django DRF, via PUT? I try to test mp3 modification (hence PUT). I have the following so far:
client = Client()
with open('my_modified_audio.mp3', 'rb') as fp:
    response = client.put(
            f"/resource/{resource_id}/",
            data={'audio': fp})

However, I get response.status_code == 415 because the serializer line in DRF's ModelViewSet
serializer = self.get_serializer(instance, data=request.data, partial=partial).
fails with
rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request.
I have tried setting format="multipart", setting the content type to json or form-encoded, nothing helped so far. The Resource model uses FileField:
class Resource(models.Model):
    audio = models.FileField(upload_to='uploads')

How can I make this put request work?

A: I think that the following will work:
The client:
import requests
...

client = Client()
files = [('audio': open('my_modified_audio.mp3', 'rb'))]
url = f"/resource/{resource_id}/"

# response = client.put(url, data=None, files=files)
# You can test it using the `requests` instead of Client()
response = requests.put(url, data=None, files=files)

The serializer:
class AudioSerializer(serializers.Serializer):
    """ AudioSerializer """
    audio = serializers.FileField(...)

    def create(self, validated_data):
        ...

    def update(self, instance, validated_data):
        ...

The view:
from rest_framework.generics import UpdateAPIView

class AudioView(UpdateAPIView):
   ...
   parser_classes = (FormParser, MultiPartParser)
   serializer_class = AudioSerializer
   ...

A: Inspired by @athansp's answer, I compared the source code of client.post and client.put and it turns out, put's implementation slightly differs from post, so a workable way of submitting files with put is:
from django.test.client import MULTIPART_CONTENT, encode_multipart, BOUNDARY

client = Client()
with open('my_modified_audio.mp3', 'rb') as fp:
    response = client.put(
        f"/resource/{resource_id}/",
        data=encode_multipart(BOUNDARY, {
            'other_field': 'some other data',
            'audio': fp,
        }),
        content_type=MULTIPART_CONTENT
    )

Lol.


Q: Change element tag name Mootools I am at the end , sooo many posts and Fiddle examples on how to change tag name of all elements on page with Jquery but NONE with mootools. Is there any way to do it? I need to convert all tr to div, not able to change the actual page html, must do it with Moo. Please help.
i have 15 tr's in a div , crazy huh!

...

I need to convert them to divs but keep all attributes and html within tr's in tact. PLEASE help! Thank you!

A: Replacing elements in mootools is easy, as long as the markup is not invalid as above.
http://jsfiddle.net/dimitar/4WatG/1/
document.getElements("#mydiv span").each(function(el) {
     new Element("div", {
        html: el.get("html")
    }).replaces(el);
});

this will replace all spans for divs in the above markup (use spans instead of trs).
as stated up, http://jsfiddle.net/dimitar/4WatG/ -> firefox strips invalid markup of TR not being a child of a table which makes it hard to target.

A: I'm just going to leave this floating here.
Element.implement({'swapTagName': function(newTagName) {
    return new Element(newTagName, {html: this.get('html')}).replaces(this);
}});

Usage:
//cleaning HTML3.2 like it's 2012
target.getElements('font[size=5pt],b').swapTagName('h2').addClass('header_paragraphs');
target.getElements('font').swapTagName('p');


Q: Passing data from bootstrap model I am trying to pass the data from bootstrap model and display it on a table. However, the problem here is I am unable to pass the data and the column only display null values. I am a newbie, so I need some help on how to pass the data Day and Session?

        Day

        Type

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

Select A Day:

          <select class="selectpicker" data-style="btn-info" multiple data-max-options="1" data-live-search="true">
            <optgroup label="Day">
              <option>Monday</option>
              <option>Tuesday</option>
            </optgroup>
          </select>

Select A Session:

          <select class="selectpicker" data-style="btn-info" multiple data-max-options="1" data-live-search="true">
            <optgroup label="Session">
              <option>Morning</option>
            </optgroup>
          </select>

        <button id="addrow" type="button" class="btn btn-primary">Add
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

A: *

*You haven't closed the  tag correctly for the "#addrow" button.

*You can extract the values from the modal like so (after you give the <select> elements a proper id:
var dayPickerSelect1 = $("#daypicker-select1").val();
var dayPickerSelect2 = $("#daypicker-select2").val();

*You can then pass the extracted values to the table like so:
<input type="text" class="form-control" name="Day' + counter + '" value="' + dayPickerSelect1 + '"/>
<input type="text" class="form-control" name="Session' + counter + '" value="' + dayPickerSelect2 + '"/>


Q: Pass null arguments to native module in React-Native android I have a react-native NativeModule with a single method
@ReactMethod
public void sendEvent(String message, Integer code) {
  ...
}

I want to be able to pass null for the code argument in js, but when I do e.g.
TestModule.sendEvent('this is a test', null);

I get
com.facebook.react.bridge.NativeArgumentsParseException: TypeError: expected dynamic type `double', but had type `null' (constructing arguments for TestModule.sendEvent at argument index 1)

How can null be passed as an argument?

A: You can't pass null in Integer values.
public void sendEvent(String message, Integer code) {
Here Integer code return invalid either pass 0 or change it to String code
So now you can pass null values.


Q: Heroku nodejs Procfile never picked up It seems that my nodejs application is never deploying on Heroku. While my build successfully completes with the following message:
[154] ./server.ts 2.1 kB {0} [built]
[238] ./src 160 bytes {0} [built]
[244] (webpack)/buildin/module.js 517 bytes {0} [built]
[259] ./dist/server/main.bundle.js 76.1 kB {0} [built]
+ 301 hidden modules
Node server listening on http://localhost:5000

I'm only just seeing Heroku's Blank app:

Other symptoms:
My builds never end:

And no dynos are being instantiated:

This is despite the fact that I'm providing a Procfile, like so:
web: npm start

See my package.json:
{
  "name": "vivonslagrasse-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "node dist/server.js",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "universal": "ng build --prod --aot && ng build --prod --app ssr --output-hashing=false && webpack --config webpack.server.config.js --progress --colors && node dist/server.js",
    "postinstall": "npm run universal"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/platform-server": "^5.2.9",
    "@angular/router": "^5.2.0",
    "@nguniversal/module-map-ngfactory-loader": "^5.0.0-beta.8",
    "@ngx-translate/core": "^9.1.1",
    "@ngx-translate/http-loader": "^2.0.1",
    "@nicky-lenaers/ngx-scroll-to": "^0.6.0",
    "ngx-cookie": "^2.0.1",
    "core-js": "^2.4.1",
    "foundation-sites": "^6.4.4-rc1",
    "rxjs": "^5.5.6",
    "ts-loader": "^3.5.0",
    "xmlhttprequest": "^1.8.0",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular/cli": "~1.7.0",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.3.1",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  },
  "engines": {
    "node": "7.7.4",
    "npm": "5.6.0"
  }
}

Note that I need to run a node server since this is an angular universal app and the initial page's contents need to be server-generated.
EDIT: I'm adding my server.ts file (the generated server.js is too long to be reproduced here)
// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';

import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';

(global as any).XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 5000;
const DIST_FOLDER = join(process.cwd(), 'dist');

// Our index.html we'll use as our template
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main.bundle');

const {provideModuleMap} = require('@nguniversal/module-map-ngfactory-loader');

app.engine('html', (_, options, callback) => {
  renderModuleFactory(AppServerModuleNgFactory, {
    // Our index.html
    document: template,
    url: options.req.url,
    // DI so that we can get lazy-loading to work differently (since we need it to just instantly render it)
    extraProviders: [
      provideModuleMap(LAZY_MODULE_MAP)
    ]
  }).then(html => {
    callback(null, html);
  });
});

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), {req});
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node server listening on http://localhost:${PORT}`);
});

Needless to say, this setup works perfectly on my development machine...
Your help will be highly appreciated. I already spent 2,5 hours on this.

A: Use process.env.port in server.js to listen
const port = process.env.port || 5000;
app.listen(port);


Q: solr: Adding content-disposition to SolrQueryResponse I have a custom request handler that is extending RequestHandlerBase.
The purpose of this handler is to search the index for the given user query. Instead of omitting the results on the browser at client side, the response data should be downloaded as a file. Here is my handleRequestBody function code
@Override

public void handleRequestBody(final, SolrQueryRequest req,final SolrQueryResponse res) {
    tempFile = File.createTempFile(UUID.randomUUID().toString(),".tmp", new File(FILE_PATH));
    writeSearchResultstoFile(tempFile);
    ContentStreamBase outConentStream = new ContentStreamBase.FileStream(tempFile);
    outConentStream.setContentType("application/download");
    rsp.add(RawResponseWriter.CONTENT, outConentStream);
}

The problem is the file is being downloaded with .part file at client side.
rsp.getResponseHeader().add("Content-Disposition", "filename=data.csv");
didn't help much. Could some please tell me how to set the Content-Disposition.

A: Since I see that you are formatting your results as CSV I am curious as to whether you have looked at the CSVResponseFormat that Solr has supported since release 3.1


Q: Trying to understand packets captured with tcpdump So I have intercepted a packet being sent from my android device to an apps server. I want to understand what my phone is sending to the server.
I have rooted the phone, and install tcpdump on it. I have used adb shell to run:
tcpdump -n -i wlan0 -w OUTPUT_FILE src host IP_ADDRESS and greater 200

I have gotten the packet on my pc and run it through wireshark.

I have been told that the long list of "........" prevalent in the ascii section is because there is no ascii representation of the specific HEX.
Is that true?
I have been able to determine the packet is not encrypted, because I can see clear text strings in the ascii that I type in the app.
I am guessing the data is either binary OR base64 encoded JSON, converted to hex and sent to the server. Is there any step I can take to further understand the structure of the data sent from my device to the remote server?
Any other tips, or random insights would be super helpful.

A:
Is that true?

Yes.

Is there any step I can take to further understand the structure of the data sent from my device to the remote server?

The captured packet includes an Ethernet Ⅱ header and an IPv4 header and a UDP header as follows:
Ethernet Ⅱ: from 20:e5:2a:4f:b9:4f (NETGEAR) to 44:80:eb:ea:ef:9b (Motorola)
IPv4: from 169.55.244.58 to 192.168.1.12, not fragmented
UDP: from port 14242 to port 48818, payload length=1406 bytes

The right chunk of the 3rd line (i.e. bb 19 43 4f 02 c8 2b a3) is the start of the application data.
To analyze the application data, you need to know what protocol the application used to send the packet and to learn the protocol.


Q: Keras TensorFlow Hub: Getting started with simple ELMO network I'm trying to get a simple ELMO model working from TensorFlow hub but, it's turning out to be a challenge.
When I run the my code, I'm getting the error: "Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'input_69:0' shape=(None, 10) dtype=string>]"
I think I'm messing up the sequence_length args or the inputs. Can anyone please help me?
import tensorflow as tf
import tensorflow_hub as hub
import re

from tensorflow import keras
import tensorflow.keras
from tensorflow.keras.layers import Input, Dense,Flatten
import numpy as np
import keras.callbacks
import io
from sklearn.model_selection import train_test_split

i = 0
max_cells = 51 #countLines()
x_data = np.zeros((max_cells, 10, 1), dtype='object')
y_data = np.zeros((max_cells, 3), dtype='float32')
seqs = np.zeros((max_cells), dtype='int32')

with io.open('./data/names-sample.txt', encoding='utf-8') as f:
    content = f.readlines()
    for line in content:
        line = re.sub("[\n]", " ", line)
        tokens = line.split()

        for t in range(0, min(10,len(tokens))):
            tkn = tokens[t]
            x_data[i,t] = tkn

        seqs[i] = len(tokens)
        y_data[i,0] = 1

        i = i+1

def build_model():
    tokens = Input(shape=[10,], dtype=tf.string)
    seq_lens = Input(shape=[], dtype=tf.int32)

    elmo = hub.KerasLayer(
        "https://tfhub.dev/google/elmo/3",
        trainable=False,
        output_key="elmo",
        signature="tokens",
    )
    out = elmo({"tokens": tokens, "sequence_len": seqs})

    model = keras.Model(inputs=[tokens, seq_lens], outputs=out)
    model.compile("adam", loss="sparse_categorical_crossentropy")
    model.summary()

    return model

x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.70, shuffle=True)

model = build_model()
model.fit(x_train, y_train,validation_data=(x_test, y_test),epochs=1,batch_size=32)

Full Error:

TypeError: An op outside of the function building code is being passed
a "Graph" tensor. It is possible to have Graph tensors leak out of the
function building context by including a tf.init_scope in your
function building code. For example, the following function will fail:
@tf.function   def has_init_scope():
my_constant = tf.constant(1.)
with tf.init_scope():
added = my_constant * 2 The graph tensor has name: input_69:0
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\temp\Simon\TempElmoNames.py", line 66, in
model = build_model()
File "C:\temp\Simon\TempElmoNames.py", line 56, in build_model
out = elmo({"tokens": tokens, "sequence_len": seqs})
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py",
line 891, in call
outputs = self.call(cast_inputs, *args, **kwargs)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_hub\keras_layer.py",
line 229, in call
result = f()
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py",
line 1081, in call
return self._call_impl(args, kwargs)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py",
line 1121, in _call_impl
return self._call_flat(args, self.captured_inputs, cancellation_manager)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py",
line 1224, in _call_flat
ctx, args, cancellation_manager=cancellation_manager)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py",
line 511, in call
ctx=ctx)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\execute.py",
line 75, in quick_execute
"tensors, but found {}".format(keras_symbolic_tensors))
_SymbolicException: Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'input_69:0' shape=(None, 10)
dtype=string>]

Here are the versions I'm working with:
Keras: 2.3.1
TF: 2.0.0
TH-hub: 0.12.0
UPDATE 1:
I upgraded Keras (2.6.0) TF (2.6.0) & TF Hub(0.12.0) and changed the build_model method on how the seqs and seq_lens are passed.
def build_model():
    tokens = Input(shape=[10,], dtype=tf.string)
    seq_lens = Input(shape=[], dtype=tf.int32)

    elmo = hub.KerasLayer(
        "https://tfhub.dev/google/elmo/3",
        trainable=False,
        output_key="elmo",
        signature="tokens",
    )
    out = elmo({"tokens": tokens, "sequence_len": seq_lens})

    model = keras.Model(inputs=[tokens, seqs], outputs=out)
    model.compile("adam", loss="sparse_categorical_crossentropy")
    model.summary()

    return model

Now I'm getting the error:

ValueError: Input tensors to a Functional must come from
tf.keras.Input. Received: [3 3 2 2 3 3 3 5 3 3 3 2 7 2 2 2 3 2 2 3 3
3 3 3 3 2 3 2 3 2 3 3 2 3 3 2 3  2 2 2 2 3 2 2 3 3 5 3 3 3 0] (missing
previous layer metadata).

A: I don't believe it is a bug rather TF gives us freedom in choosing each method. While we can mix match the layer subclass with keras functional api, I guess we can't make the model subclass work with the Model api of keras. This is where, in my opinion the distinction between eager execution and keras graph mode comes into conflict giving rise to this "SymbolicException".
Making TF aware beforehand what mode it should execute solves it.

A: Ok finally got it working. The first I did it upgraded:
Keras: 2.2.4
TF: 1.15.0
TF: 0.12.0

Next changed my code to use the right version of ELMO model:
import tensorflow_hub as hub
import tensorflow as tf

elmo = hub.Module("https://tfhub.dev/google/elmo/3", trainable=False)

from tensorflow.keras.layers import Input, Lambda, Bidirectional, Dense, Dropout, Flatten, LSTM
from tensorflow.keras.models import Model

def ELMoEmbedding(input_text):
    return elmo(tf.reshape(tf.cast(input_text, tf.string), [-1]), signature="default", as_dict=True)["elmo"]

def build_model():
    input_layer = Input(shape=(1,), dtype="string", name="Input_layer")
    embedding_layer = Lambda(ELMoEmbedding, output_shape=(1024, ), name="Elmo_Embedding")(input_layer)
    BiLSTM = Bidirectional(LSTM(128, return_sequences= False, recurrent_dropout=0.2, dropout=0.2), name="BiLSTM")(embedding_layer)
    Dense_layer_1 = Dense(64, activation='relu')(BiLSTM)
    Dropout_layer_1 = Dropout(0.5)(Dense_layer_1)
    Dense_layer_2 = Dense(32, activation='relu')(Dropout_layer_1)
    Dropout_layer_2 = Dropout(0.5)(Dense_layer_2)
    output_layer = Dense(3, activation='sigmoid')(Dropout_layer_2)
    model = Model(inputs=[input_layer], outputs=output_layer, name="BiLSTM with ELMo Embeddings")
    model.summary()
    model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
    return model
elmo_BiDirectional_model = build_model()

import numpy as np
import io
import re
from tensorflow import keras

i = 0
max_cells = 300
x_data = np.zeros((max_cells, 1), dtype='object')
y_data = np.zeros((max_cells, 3), dtype='float32')

with tf.Session() as session:
    session.run(tf.global_variables_initializer())
    session.run(tf.tables_initializer())
    model_elmo = elmo_BiDirectional_model.fit(x_data, y_data, epochs=100, batch_size=5)
    train_prediction = elmo_BiDirectional_model.predict(x_data)


Q: Where is defined the TgtOutFormat type in PDFtoolkit VCL library? I have a problem to set watermark image format in the TgtImageWatermarkTemplate component (which is part of the Gnostice PDFtoolkit VCL library). I have the following code:
var
  Watermark: TgtImageWatermarkTemplate;
begin
  ...
  // create and set watermark properties
  Watermark := TgtImageWatermarkTemplate.Create;
  Watermark.ImageFormat := ofJPEG; // <- this line fails the compilation
  ...
end;

But it fails to compile with the following error:

[DCC Error] Unit1.pas(186): E2003 Undeclared identifier: 'ofJPEG'
  [DCC Fatal Error] Project1.dpr(5): F2063 Could not compile used unit 'Unit1.pas'
  Failed Elapsed time: 00:00:01.5

In which unit is the ofJPEG identifier declared (I think it's member of the TgtOutFormat enumeration)? Which unit should I add to my uses clause?

A: Please include gtCstPDFDoc unit in your PAS file. The enumeration TgtImageFormat is from that.
UPDATE: The enumeration values start with if and so it is ifJPEG.


Q: How to add custom header to AFNetworking on a JSONRequestOperation Hi, I have the following code accessing a URL:
NSString * stringURL = [NSString stringWithFormat:@"%@/%@/someAPI", kSERVICE_URL, kSERVICE_VERSION];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]];

AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    completionHandler(JSON, nil);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    completionHandler(nil, error);
}];

But I want to pass the user token as a parameter on HEADER, like X-USER-TOKEN.
Cant find it on AFNetworking documentation, should I change the operation type?

A: I did this :)
[manager.requestSerializer setValue:[NSString stringWithFormat:@"Token token=\"%@\"", _userObj.oAuth] forHTTPHeaderField:@"Authorization"];

A: Use AFHTTPClient or subclass it!
You can set default headers with -setDefaultHeader:value: like this :
[self setDefaultHeader:@"X-USER-TOKEN" value:userToken];

You can check the documentation

A: If you have a layer of abstraction, let's say APIManager,
then you should do the following inside a particular method
 [[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:@"X-Register"];

A: NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];

[request setValue: @"X-USER-TOKEN"  forHTTPHeaderField:@"< clientToken >"];

[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]


Q: Making a android button’s background translucent, Is there a way to make an android button’s background translucent within xml code,
So the button has no background drawable?

A: android:background="@android:color/transparent"

You can also set your own colors:
android:background="#80000000"

The first two hex characters represent opacity. So #00000000 would be fully transparent. #80000000 would be 50% transparent. #FF000000 is opaque.
The other six values are the color itself. #80FF8080 is a color I just made up and is a translucent sort of pinkish.

A: Set the background to the standard android transparent color.
In Code:
myButton.setBackground(getResources().getColor(android.R.color.transparent));

In xml:
android:background="@android:color/transparent"

A: The best way is to create a selector.


Q: AppDelegate.swift line 0 type metadata accessor for _ContiguousArrayStorage crash There is a strange crash happening in my code when I try upgrade the app version.
Here is the crash report for the crash :-
  Crashed: com.apple.root.user-initiated-qos
  0  libswiftCore.dylib             0x102f6f95c specialized _assertionFailure(_:_:file:line:flags:) + 164
  1  Quickride                      0x1011b02f8 type metadata accessor for _ContiguousArrayStorage<String> (AppDelegate.swift)
  2  Quickride                      0x1011a1cfc closure #1 in closure #1 in AppDelegate.persistentContainer.getter (AppDelegate.swift)
  3  Quickride                      0x1015196cc thunk for @callee_owned (@owned NSPersistentStoreDescription, @owned Error?) -> () (UserDataCache.swift)
  4  CoreData                       0x184f3d6d0 -[NSPersistentStoreCoordinator _doAddPersistentStoreWithDescription:privateCopy:completionHandler:] + 920
  5  CoreData                       0x184f3d8a0 -[NSPersistentStoreCoordinator addPersistentStoreWithDescription:completionHandler:] + 172
  6  CoreData                       0x18500100c -[NSPersistentContainer loadPersistentStoresWithCompletionHandler:] + 484
  7  Quickride                      0x1011a1c6c AppDelegate.persistentContainer.getter (AppDelegate.swift:670)
  8  Quickride                      0x10123a72c specialized static  CoreDataHelper.getNSMangedObjectContext() (CoreDataHelper.swift:18)
  9  Quickride                      0x101131664 specialized static ContactPersistenceHelper.clearAllContacts() (ContactPersistenceHelper.swift:113)
  10 Quickride                      0x10123efd0 specialized UserModuleSessionManager.clearUserPersistentStore() (UserModuleSessionManager.swift:103)
  11 Quickride                      0x1010417d4 specialized QRSessionManager.performSessionChangeOperationOnModule(moduleSessionHandler:sessionChangeOperationId:) (QRSessionManager.swift)
  12 Quickride                      0x10103df24 QRSessionManager.callSessionChangeOperationOnAllModules(sessionChangeOperationId:isShutdownSequence:) (QRSessionManager.swift:256)
  13 Quickride                      0x10103d410 QRSessionManager.onResumeUserSession() (QRSessionManager.swift:159)
  14 Quickride                      0x1013125b0 SessionManagerController.resumeUserSession(sessionChangeCompletionListener:) (SessionManagerController.swift:82)
  15 Quickride                      0x10128b0c8 closure #1 in AppStartupHandler.resumeUserSessionAndNavigateToAppropriateInitialView() (AppStartupHandler.swift:38)
  16 Quickride                      0x100ee5784 thunk for @callee_owned () -> () (RideManagementModuleSessonHandler.swift)
  17 libdispatch.dylib              0x181e50aa0 _dispatch_call_block_and_release + 24
  18 libdispatch.dylib              0x181e50a60 _dispatch_client_callout + 16
  19 libdispatch.dylib              0x181e5ddfc _dispatch_root_queue_drain + 924
  20 libdispatch.dylib              0x181e5d9fc _dispatch_worker_thread3 +       120
  21 libsystem_pthread.dylib        0x182183fac _pthread_wqthread + 1176
  22 libsystem_pthread.dylib        0x182183b08 start_wqthread + 4

Any help guys on whats this strange crash all about ? Tried a lot but couldn't figure you..... Thanks in advance


Q: Problems after Importing an android project from github into Eclipse I'm trying to tinker with this project and am having some issues importing it.
https://github.com/HoloAddict/FeedEx
I'm a beginner still, and have made a couple of test projects from scratch, but I think I'd learn a little faster by going through working code in a larger project. Just can't get rid of errors to even build the existing code. These are the steps I have taken:

*

*imported it in as a Git project (file - Import - Git - Projects from Git)

*gen folder error (does not exist or not source) - right clicked on gen, Buld path - Use as a source folder. This made that particular error go away

*all the src files were listed as src.net.fred... packages, so all the imports were errors. Right click - build path - configure build path - added Feedex/src in build path, got rid of those errors.

*have the R.java problem... tried many clean-build approaches, no luck. Also tried taking one from a clean project, creating package net.fred.feedex in gen, creating file R.java, and putting code in from a clean project, but no luck. It did make the import R go away, but of course left many errors where the res class references are broken, again because that R file is missing (I think).

So that's where I am. It seems like I have an R.java problem, but I may have messed up on one of the other steps. Either way, thanks for the help.

A: When you imported the project did you check the "Copy projects into workspace"?
If not import your project again and see if this problem still continues.


Q: RES_NOT_FOUND after login using JAAS I am using JAAS to authenticate users accessing the protected area of my web application. The login page looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <meta http-equiv="Content-Type" content="text/html; UTF-8" />
    <title>Test</title>
</h:head>
<h:body>
    <ui:composition template="template/common/commonLayout.xhtml">
        <ui:define name="content">
            <form name="loginForm" method="post" action="j_security_check">

                        Login to the your application:

                        Select something:
                        <h:selectOneMenu>
                                <f:selectItems value="#{loginScreenBean.listSomething}" />
                            </h:selectOneMenu>

                        Name:
                        <input type="text" name="j_username" />

                        Password:
                        <input type="password" name="j_password" />

                        <input type="submit" value="Go" />

            </form>
        </ui:define>
    </ui:composition>
</h:body>

My web-xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>patchit</display-name>
  <welcome-file-list>
    <welcome-file>test.html</welcome-file>
  </welcome-file-list>
  <security-role>
    <role-name>admin</role-name>
  </security-role>
  <security-constraint>
    <display-name>Example Security Constraint</display-name>
    <web-resource-collection>
      <web-resource-name>Protected Area</web-resource-name>
      <url-pattern>/protected/*</url-pattern>
      <http-method>DELETE</http-method>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
      <http-method>PUT</http-method>
    </web-resource-collection>
    <auth-constraint>
      <role-name>admin</role-name>
    </auth-constraint>
  </security-constraint>
  <login-config>
    <auth-method>FORM</auth-method>
    <realm-name>Example Form-Based Authentication Area</realm-name>
    <form-login-config>
      <form-login-page>/login.xhtml</form-login-page>
      <form-error-page>/login-error.xhtml</form-error-page>
    </form-login-config>
  </login-config>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
</web-app>

my jaas config looks like this:
CustomLogin {
    de.kungfuzius.test.security.SimpleLoginModule
    sufficient;
};

so when I open a page in the protected area like contextpath/protected/test.xhtml I am presented the login.xhtml with the login form. Once I hit the submit button the user is authenticated, but instead of being forwarded/redirected to the initially requested page I am redirected to contextpath/protected/RES_NOT_FOUND. To check if the user is really authenticated I tried to access contextpath/protected/test.xhtml again at it worked.
Any help is greatly appreciated.
Thanks!

A: wow, interesting behavior. I had a look at the requests using fiddler and I found a request to context/protected/RES_NOT_FOUND. This request came from a css file which was referenced in my template, but did not exist yet.
When I remove this reference to the style sheet it works!!!


Q: using font-awesome in fnCreatedCell Recently learned a new way to use data-attributes within a datatable.
Previously, I would code the columns in this manner (please note the font-awesome tags):
 "columns": [{
    "data": "",
    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
    {
      $(nTd).html("<a href='#' title='Edit Account' class='modAccount'
      data-voyid='"+oData.VOYID+"' data-servicename='"+oData.SERVICE_NAME+"'
      data-vesselname='"+oData.VESSEL_NAME+"' data-voyage='"+oData.VOYAGE+"'
      data-bound='"+oData.BOUND+"' data-cargoweek='"+oData.CARGO_WEEK+"'
      data-cargoyear='"+oData.CARGO_YEAR+"' data-allocation='"+oData.ALLOCATION+"'
      data-importvoyage='"+oData.IMPORT_VOYAGE+"' data-adddate='"+oData.ADD_DATE+"'
      data-adduser='"+oData.ADD_USER+"' data-moddate='"+oData.MOD_DATE+"'
      data-moduser='"+oData.MOD_USER+"'> ");
    },

The method I just learned follows this format:
"columns": [{
    "data": "",
    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
    {
       $('', {
       'href': '#',
       'title': 'Edit Account',
       'class': 'modAccount',
       'data-voyid': oData.VOYID,
       'data-servicename': oData.SERVICE_NAME,
       'data-vesselname': oData.VESSEL_NAME,
       'data-voyage': oData.VOYAGE,
       'data-bound': oData.BOUND,
       'data-cargoweek': oData.CARGO_WEEK,
       'data-cargoyear': oData.CARGO_YEAR,
       'data-allocation': oData.ALLOCATION,
       'data-importvoyage': oData.IMPORT_VOYAGE,
       'data-adddate': oData.ADD_DATE,
       'data-adduser': oData.ADD_USER,
       'data-moddate': oData.MOD_DATE,
       'data-moduser': oData.MOD_USER,
       'text': ' ' <-- does not work
       }).appendTo(nTd);
     }
   },

I had no problem bringing in the font-awesome icon with the first piece of code.
The second piece of code is where I need the icons now.
If  you'll notice in the 'text' section in the second piece of code, I tried to pull in the font-awesome icons there.  But on screen, I only see the code, not the icon.
How can I fix this to include the font-awesome icons?
Thank you.

A: You're adding HTML so you supply the string to the html property, instead of text in the object initialiser:
'html': ' '


Q: Decrypting a string to Byte array I was doing encrypting a array of string containing only 0s and 1s like this :
public String[] binaryToText1(String[] binary1, int lengthofshares) {
    String[] encrptedfinally = new String[lengthofshares];
    for(int tt = 0; tt < lengthofshares; tt++) {
        String ss2 = "";
        String ss = binary1[tt];
        String mynextChar;
        ss2 = new java.math.BigInteger(ss, 2).toString(16);
        encrptedfinally[tt] = ss2;
    }
    return encrptedfinally;
}

Here lengthofshares is just the size of string array binary1.But i got stuck when i tried to convert it back to an String array of 0 and 1
I was not able to come up with a solution.
Function of decryption is somewhat like this :
public String[] textToBinary(String[] alpha, int myK) {
    String[] ans = new String[myK + 3];
    for(int t = 0; t < myK; t++) {
        String s = alpha[t];
        byte bytes[] = new byte[s.length()];
        char c[] = s.toCharArray();
        int i;
        for(i = 0; i < s.length(); i++) {
            bytes[i] = (byte) c[i];
        }
        StringBuilder binary = new StringBuilder();
        for(byte b : bytes) {
            int val = b;
            for(i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
        }
        ans[t] = binary.toString();
    }
    return ans;
}

But results are different.Please help.Am not able to get the reason for it being wrong

A: Unfortunately, I don't really understand your code, and I also couldn't figure out if you just want plain String-to-byte conversion or if you also want to do some naive encrypting.
In any case, I think the code below does most of what you want. It uses bitmasks to extract the bits from a 0 to 255 integer representing a char (char + 127).
Similary, it uses bitwise OR to convert the binary String[] representation of the String back to chars and finally, back to a String.
public static void main(String[] args)
{
    String test = "Don't worry, this is just a test";
    List<String> binary = stringToBinary(test);
    System.out.println(binary);
    System.out.println(binaryToString(binary));
}

public static List<String> stringToBinary(String input)
{
    LinkedList<String> binary = new LinkedList<String>();
    char[] input_char = input.toCharArray();
    for (int c = input_char.length - 1 ; c >= 0; c--)
    {
        int charAsInt = input_char[c] + 127; // Char range is -127 to 128. Convert to 0 to 255
        for (int n = 0; n < 8; n++)
        {
            binary.addFirst((charAsInt & 1) == 1 ? "1" : "0");
            charAsInt >>>= 1;
        }
    }
    return binary;
}

public static String binaryToString(List<String> binary)
{
    char[] result_char = new char[binary.size() / 8];
    for (int by = 0; by < binary.size() / 8; by++)
    {
        int charAsInt = 0;
        for (int bit = 0; bit < 8; bit++)
        {
            charAsInt <<= 1;
            charAsInt |= binary.get(by * 8 + bit).equals("1") ? 1 : 0;
        }
        result_char[by] = (char) (charAsInt - 127);
    }
    return new String(result_char);
}


Q: click returns only the first item value in jQuery I have many products with the same class name and I want a user click on the item to return only the clicked item values but my code is returning the value of the first product only.one more thing i want when user click on images the record stores in the cart but here in my case when user click on image the selected product value returned and again when user click on another image the previous value get replace with this one i dont want to replace it i want to add in other li how it can be done. Here is my code:

bellle belle belle 25cl

2 Unit(s) at PKR 0.8/Unit(s)

          PKR 1.6

          processor amd 8-core

           PKR 1980.0

 processor amd 8-core

           PKR 1980.0

Total:PKR 1993.0

Taxes:PKR 0.0

pkr 800.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 800.0

Beverg

The script i have written for it is here.

A: You need too use this, this inside a JQuery event handler is the DOM element that has the handler attached.
Use
  var price=$(this).find("p").html();
  var product=$(this).find("h1").html();

instead of
  var price=$(".box2 p").html();
  var product=$(".box2 h1").html();

A: Use
$(this).find('p') //or  $(this).find('h1')

Instead of
$(".box2 p").html()

A: $(document).ready(function() {
  $('.box2').click(function(){
      var price=$( this).find('p').html();
      var product=$( this).find('h1').html();
      $(".add li:first-child").text(product+ price);

  });
});

Your jquery should looks like
Demo

A: You can use like this (A faster way):
$('.box2').click(function(){
      var price=$(".box2 p", this).html();
      var product=$(".box2 h1", this).html();
      $(".add li:first-child", this).text(product);
      $(".add li:nth-child(2)", this).text(price);
  });

A:

A: try
  var price=$( this).find('p').html();