text:
Q: Trying to use docker-compose but unknown error happens I am trying to install traggo docker. I have the latest docker and latest docker CE installed.
docker-compose.yml:
services:
  traggo:
    image: traggo/server:latest
    ports:
      - 3030:3030
    environment:
      TRAGGO_DEFAULT_USER_NAME: "admin"
      TRAGGO_DEFAULT_USER_PASS: "mynewpassword"
    volumes:
      - ./traggodata:/opt/traggo/data

When I try to run the docker-compose up -d command, I get following errors. I have never seen these errors before:
mead650@mead650-vm:~/docker/traggo$ sudo docker-compose up -d && docker-compose logs -f
Creating traggo_traggo_1 ... done
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 704, in urlopen
    httplib_response = self._make_request(
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 399, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib/python3.10/http/client.py", line 1282, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib/python3.10/http/client.py", line 1328, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.10/http/client.py", line 1277, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.10/http/client.py", line 1037, in _send_output
    self.send(msg)
  File "/usr/lib/python3.10/http/client.py", line 975, in send
    self.connect()
  File "/usr/lib/python3/dist-packages/docker/transport/unixconn.py", line 30, in connect
    sock.connect(self.unix_socket)
PermissionError: [Errno 13] Permission denied

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 440, in send
    resp = conn.urlopen(
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 786, in urlopen
    retries = retries.increment(
  File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 550, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/usr/lib/python3/dist-packages/six.py", line 718, in reraise
    raise value.with_traceback(tb)
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 704, in urlopen
    httplib_response = self._make_request(
  File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 399, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib/python3.10/http/client.py", line 1282, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib/python3.10/http/client.py", line 1328, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.10/http/client.py", line 1277, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.10/http/client.py", line 1037, in _send_output
    self.send(msg)
  File "/usr/lib/python3.10/http/client.py", line 975, in send
    self.connect()
  File "/usr/lib/python3/dist-packages/docker/transport/unixconn.py", line 30, in connect
    sock.connect(self.unix_socket)
urllib3.exceptions.ProtocolError: ('Connection aborted.', PermissionError(13, 'Permission denied'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/docker/api/client.py", line 214, in _retrieve_server_version
    return self.version(api_version=False)["ApiVersion"]
  File "/usr/lib/python3/dist-packages/docker/api/daemon.py", line 181, in version
    return self._result(self._get(url), json=True)
  File "/usr/lib/python3/dist-packages/docker/utils/decorators.py", line 46, in inner
    return f(self, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/docker/api/client.py", line 237, in _get
    return self.get(url, **self._set_request_timeout(kwargs))
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 542, in get
    return self.request('GET', url, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 529, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python3/dist-packages/requests/sessions.py", line 645, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 501, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', PermissionError(13, 'Permission denied'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/bin/docker-compose", line 33, in <module>
    sys.exit(load_entry_point('docker-compose==1.29.2', 'console_scripts', 'docker-compose')())
  File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 81, in main
    command_func()
  File "/usr/lib/python3/dist-packages/compose/cli/main.py", line 200, in perform_command
    project = project_from_options('.', options)
  File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 60, in project_from_options
    return get_project(
  File "/usr/lib/python3/dist-packages/compose/cli/command.py", line 152, in get_project
    client = get_client(
  File "/usr/lib/python3/dist-packages/compose/cli/docker_client.py", line 41, in get_client
    client = docker_client(
  File "/usr/lib/python3/dist-packages/compose/cli/docker_client.py", line 170, in docker_client
    client = APIClient(use_ssh_client=not use_paramiko_ssh, **kwargs)
  File "/usr/lib/python3/dist-packages/docker/api/client.py", line 197, in __init__
    self._version = self._retrieve_server_version()
  File "/usr/lib/python3/dist-packages/docker/api/client.py", line 221, in _retrieve_server_version
    raise DockerException(
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', PermissionError(13, 'Permission denied'))

I tried traggo's directions, and they do not have the help or Google search. I have two machines with docker and protainor installed. I have Ubuntu Server, the latest version. I never have issues with using docker-compose from the ether of these machines.


text:
Q: $wpdb->prepare with ON DUPLICATE KEY UPDATE I just took this code from $wpdb Codex page, and modified my existing Insert query:
$table = $wpdb->prefix . 'user_req';

$post_id = explode('_', $_POST['post_id']);
$user_id = $_POST['user_id'];
$wpdb->insert(
        $table,
        array(
            'user_id' => $user_id,
            'post_id' => $post_id[1]
        ),
        array(
            '%d',
            '%d'
        )
    );

into:
$wpdb->query( $wpdb->prepare(
            "
                INSERT INTO {$wpdb->prefix}user_req
                ( user_id, post_id )
                VALUES ( %d, %d )
                ON DUPLICATE KEY UPDATE
                user_id = VALUES(user_id), post_id = VALUES(post_id)
            ",
            $user_id,
            $post_id[1]
        ) );

Because I need to prevent the duplicate entries entering into the database. But still the duplicate entries are entering into the db while the insert query is functioning properly. To add the ON DUPLICATE KEY UPDATE portion, I followed the s_ha_dum's Answer on another thread.
What am I doing wrong?

A: It's my fault. Got the solution after @Otto's comment:

Do you actually have a duplicate key here? What is the structure of
user_req and what are the keys and indexes?

Here's how my SQL query should be:
INSERT INTO {$wpdb->prefix}user_req
                ( user_id, post_id )
                VALUES ( %d, %d )
                WHERE NOT EXISTS (
                  SELECT * FROM
                  {$wpdb->prefix}user_req.user_id = user_id
                  AND
                  {$wpdb->prefix}user_req.post_id = post_id
                )

Fixed now. Thanks to Otto.
UPDATE
Though I said, it's solved, but actually, it's not. The code somehow was not working and not even inserting data (Details here). So with the knowledge I had from the others, and with assistance of my colleague Mr. Ariful Haque, I did it with two different but interlocking queries:
    $alreadyGot = $wpdb->get_results(
                        "SELECT
                        COUNT(*) AS TOTALCOUNT
                        FROM {$table}
                        WHERE ( user_id = $user_id AND post_id = $post_id[1] )
                            AND ( order_id = '' )"
                    );

    $count = $alreadyGot[0]->TOTALCOUNT; //if there's any duplicate, it'd return 1

    // if the count return 1, do nothing, but else insert the data
    if( $count > 0 ) {
        //do nothing
    } else {
        $wpdb->insert(
            $table,
            array(
                'user_id' => $user_id,
                'post_id' => $post_id[1]
            )
        );
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: System.Reflection.TargetInvocationException in xamarin with web service I'm new in xamarin, I used web service (asmx) with xamarin and I got it on error follow:
Erreur :
MainActivity :
web service :
web.config :
Thanks in advance.


text:
Q: Read file by fscanf and after it's by fgets given a file (file.txt) with the following content:

123 456
  789 101

I don't understand why after that I read from the file the first line (by fscanf) it's not work to read the second line.
int main() {
    FILE* fp = fopen("file.txt", "r");
    if (fp == NULL)
        return 1;
    int n1, n2;
    fscanf(fp, "%d %d", &n1, &n2);
    char buffer[10]="";
    fgets(buffer, 10, fp);
    printf("%s", buffer);
}

What is the problem? (I tried to add \n in the format of fscanf and then it's works, but I don't understand why I must add \n to the format of fscanf?)


text:
Q: single click text selection in eclipse java editor my eclipse has started to select words as soon as the cursor is somewhere inside the word. used to be the word had to be double clicked to be selected but now it just does it when the cursor is inside a word.
i have no idea if i accidentally changed something but i couldn't find any solution on google so i hope you guys can help.
i find the automatic selection and extremely distracting like this but turning it off completely i also not very desirable so i'm hoping it's a simple setting i was unable to find.


text:
Q: ProxyPreserveHost On for one reverse proxy only? We use a third-party server that does not appear to handle comma-delimited X-FORWARDED-HOST values properly. In summary, it generates HTML pages containing invalid URLs like http://externalsite_address, internalsite_address/blah/blah/blah when it is reached through proxies (this scenario is described in more detail at: http://forums.arcgis.com/threads/66787-Multiple-Reverse-Proxies?p=306157). Organizationally, we have no choice but to use this third-party server and it's not open source, so we can't fix anything ourselves. I have been trying for two weeks to overcome this problem but, given our organization's web architecture, still can't get things to work as desired. What we would like to see in those HTMLs' URLs is http://externalsite_address/blah/blah/blah.
In a test environment, I have learned that I can get things to work as desired by setting ProxyPreserveHost On for the server acting as the external site and then on the internal site add the directive "RequestHeader unset X-Forwarded-Host". Everything works fine doing this. Unfortunately, the real external site's configuration is a proxy server for all the other servers in our organization and we've been refused permission to introduce a server configuration change like this because it may impact other applications that exist on other internal servers in the organization.
In looking at the documentation for ProxyPreserveHost, I find that it can also be set within the context of a VirtualHost. However, I'm not sure how to define something like that in this case. All web traffic into our organization has to be routed through this externalsite_address and there is only a single RewriteRule that forwards appropriate traffic to our specific internalsite_address through a proxy, like this:
RewriteRule ^/atlas(.*)$ http://internalsite_address/atlas$1 [P,L,QSA]

Is there some way I can define that as a VirtualHost with the ProxyPreserveHost On within it? Everything I've read thus far suggests that a VirtualHost needs a different address or port and couldn't be used with the same address as the organization's. That is, we still need people to reach our internal server via http://externalsite_address/atlas, so I don't think setting up a VirtualHost is an option here...am I correct or just misunderstanding the documentation?
Assuming that I can't use the ProxyPreserveHost directive because it is only valid within the server configuration or a VirtualHost, I've been trying to figure out some way to accomplish this on our internal server only. I found Can I turn off an Apache Directive then turn it on in an include? which suggested this code:
<Proxy "http://${build.replace.host}/">
  RequestHeader set Host ${build.replace.external.host}
</Proxy>
RewriteRule      ^/proxypath/ http://${build.replace.external.host}/path/to/resource.html [P]
ProxyPassReverse /proxypath/ http://${build.replace.external.host}/path/to/resource.html

However, I couldn't figure out how I could set the Host value properly because, while external users must come through our externalsite_address, our internal users can, do and must continue to be able to come directly through our internalsite_address. So, sometimes that Host value should say http://externalsite_address/ and other times http://internalsite_address/. Really, what I would like to be able to do (but have no idea how or if it is even possible) is to somehow determine if the X-FORWARDED-HOST value is set and if so, set the Host in the header to be the first value listed in the string and then, if necessary, turn on the ProxyPreserveHost so that value is maintained through subsequent proxies.
Another way I found of solving this is to introduce another proxy definition on our external server that goes directly to the third-party server given a particular URL as follows (note the "rest" after "atlas", which is always there for requests that are ultimately handled by that server):
RewriteRule ^/atlas/rest/(.*)$ http://internalsite_address/atlas/rest/$1 [P,L,QSA]

Unfortunately, doing this would require poking a hole through a firewall into another zone of the system architecture and that has also been refused. The external server can proxy to our internal server (which is in the same zone) and our internal server (which is not directly visible externally) is the only one that has all the permissions defined to allow requests to get at all the other servers that are used to deliver web applications which exist in another zone. Please don't ask me to justify any of this, the architecture was dictated to us and we're just trying to figure out how to work within it.
Can anyone suggest anything that will help me achieve what I am trying to accomplish here? Even something I haven't found yet? Or, alternatively, is there some way that I can define a VirtualHost on the external server so I can set the ProxyPreserveHost flag on for only those requests that are routed to our internal server?
Really, at this point, I'd appreciate just about any clues...
Cheers,
jtm


text:
Q: AWS Cognito User Pool + Facebook Login iOS I have started integrating AWS Cognito User Pools into my app and the signup + login works (I have followed this tutorial: https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-integrating-user-pools-ios.html)
Now I'm struggling to properly integrate a Facebook login. This is what I do:
After the user has successfully signed in with facebook (using the facebook SDK), I'm getting the token and calling this function:
func signInFacebook(){

    let customProviderManager = CustomIdentityProvider(tokens: nil)

    self.credentialsProvider = AWSCognitoCredentialsProvider(
        regionType:CognitoIdentityUserPoolRegion,
        identityPoolId: CognitoIdentityPoolId,
        identityProviderManager: customProviderManager)

    let configuration = AWSServiceConfiguration(region:CognitoIdentityUserPoolRegion, credentialsProvider: self.credentialsProvider!)
    AWSServiceManager.default().defaultServiceConfiguration = configuration
}

My CustomIdentityProvider class looks like this:
class CustomIdentityProvider: NSObject, AWSIdentityProviderManager {
var tokens : NSDictionary?

init(tokens: NSDictionary?) {
    self.tokens = tokens
}

func logins() -> AWSTask<NSDictionary> {
    if let fbToken = AccessToken.current?.authenticationToken {
        return AWSTask(result: [AWSIdentityProviderFacebook: fbToken])
    } else if let googleToken = GIDSignIn.sharedInstance().currentUser.authentication.idToken {
        return AWSTask(result: [AWSIdentityProviderGoogle: googleToken])
    }

    return AWSTask(error:NSError(domain: "Social login", code: -1 , userInfo: ["Social login" : "No current social access token"]))
}

}

After signInFacebook() is called, I also call
self.credentialsProvider?.credentials().continueOnSuccessWith { (task:AWSTask<AWSCredentials>) -> Any? in
                print("credentials: \(task.result!)")
                return nil
}

and it prints some data in the log which looks fine.
But for some reason it doesn't seem to link properly everything together.
When I'm calling my backend to fetch some data, I usually do it like this:
I call self.user?.getSession().continueOnSuccessWith (user is an instance of AWSCognitoIdentityUser) and inside the closure I build the request where I put the token in the header. But if there are no tokens, the SDK shows my login screen. And this is what happens all the time. I would expect the user object to be updated with the correct tokens after the social login with Facebook has succeeded. What am I doing wrong?


text:
Q: Best Practices for modularizing Selenium RC test scripts I am creating Selenium RC test scripts in Visual Studio (C#). I am
struggling with re-factoring the tests; all my tests are in a single
file. I would appreciate any input and/or pointers to websites, books,
etc. to learn about modularizing the tests.
I have to run the same tests on different sites (same application but
configured differently for different clients and logins) which are 95%
same. Would anybody like to provide some good examples or best
practices to do this?
Thanks!

A: Best practise for writing Selenium tests or any UI tests is Page Object Model which is the idea that you create an Object for each of the pages. Each of these objects abstract the page so when you write a test it doesnt really look like you have been working with Selenium.
So for a blog you would do something like this to create an object for the home page
public class Home
{
    private readonly ISelenium _selenium;

    /// <summary>
    /// Instantiates a new Home Page object. Pass in the Selenium object created in the test SetUp().
    /// When the object in instantiated it will navigate to the root
    /// </summary>
    /// <param name="selenium">Selenium Object created in the tests
    public Home(ISelenium selenium)
    {
        this._selenium = selenium;
        if (!selenium.GetTitle().Contains("home"))
        {
            selenium.Open("/");
        }
    }

    /// <summary>
    /// Navigates to Selenium Tutorials Page. Selenium object wll be passed through
    /// </summary>
    /// <returns>SeleniumTutorials representing the selenium_training.htm</returns>
    public SeleniumTutorials ClickSelenium()
    {
        _selenium.Click("link=selenium");
        _selenium.WaitForPageToLoad("30000");
        return new SeleniumTutorials(_selenium);
    }

    /// <summary>
    /// Click on the blog or blog year and then wait for the page to load
    /// </summary>
    /// <param name="year">blog or blog year
    /// <returns>Object representing /blog.* pages</returns>
    public Blog ClickBlogYear(string year)
    {
        _selenium.Click("link=" + year);
        _selenium.WaitForPageToLoad("30000");
        return new Blog(_selenium);
    }
    // Add more methods as you need them
}

then you would create a test that looks like the following
[TestFixture]
public class SiteTests
{
    private ISelenium selenium;
    [SetUp]
    public void Setup()
    {
        selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.theautomatedtester.co.uk");
        selenium.Start();
    }

    [TearDown]
    public void Teardown()
    {
        selenium.Stop();
    }

    [Test]
    public void ShouldLoadHomeThenGoToXpathTutorial()
    {
        Home home = new Home(selenium);
        SeleniumTutorials seleniumTutorials = home.ClickSelenium();
        SeleniumXPathTutorial seleniumXPathTutorial = seleniumTutorials.ClickXpathTutorial();
        Assert.True(seleniumXPathTutorial.
                    IsInputOnScreen(SeleniumXPathTutorial.FirstInput));
        Assert.True(seleniumXPathTutorial
                    .IsInputOnScreen(SeleniumXPathTutorial.SecondInput));
        Assert.True(seleniumXPathTutorial
                    .IsInputOnScreen(SeleniumXPathTutorial.Total));
    }
}


text:
Q: Setting up State and Cities Rails Models, ActiveRecord Associations and Form I wanted to know the best way to implement the following:

*

*Users can create a Post and each Post is associated with a US City and State.

*I wanted to have a form where there is a dropdown box that a user can select the State and select the relevant City for example: [Hollywood] [California].
I have setup a State and City model.
The State model:
# == Schema Information
#
# Table name: states
#
#  id         :integer          not null, primary key
#  name       :string           default(""), not null
#  short      :string           default(""), not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class State < ApplicationRecord
  has_many :cities
end

The City model:
# == Schema Information
#
# Table name: cities
#
#  id         :integer          not null, primary key
#  name       :string
#  state_id   :integer
#  created_at :datetime         not null
#  updated_at :datetime         not null
#
# Indexes
#
#  index_cities_on_state_id  (state_id)
#

class City < ApplicationRecord
  belongs_to :state
end

With the Post model
# == Schema Information
#
# Table name: posts
#
#  id              :integer          not null, primary key
#  title           :string           default(""), not null
#  body            :string           default(""), not null

class Post < ApplicationRecord
end

With the Post model I thought I would to a belongs_to and has_many association with references/foreign key setup like:
class Post < ApplicationRecord
  belongs_to :city
  belongs_to :state
end

class City < ApplicationRecord
  belongs_to :state
  has_many :posts
end

class State < ApplicationRecord
  has_many :cities
  has_many :posts
end

The view would use a form_for with a grouped_collection for cities and collection for the states but I don't think this is a good implementation because:

*

*Selecting the city already as the association with the state. It seems redundant having the user select both model options?

*The dropdown box in view will load 60000 city records and it will slow down the browser.

I wanted to know if a Polymorphic association would fit my use case and if someone can forward me in the right direction.

My thoughts: I was thinking something where the user selects the the State in a dropdown box eg. California, but enters the city in a text field and if the city does not exists in Cities table it create it, otherwise it will link to it?
Thanks for your help.

A: What you want is a has_one through: association. This indirect relation tells rails to join through another association and removes the need for a duplicated foreign key.
class Post < ApplicationRecord
  belongs_to :city
  has_one :state, through: :city
end

To create a full hierarchy you would do it like so:
class Post < ApplicationRecord
  belongs_to :city
  has_one :state, through: :city
  has_one :country, through: :state
end

class City < ApplicationRecord
  belongs_to :state
  has_one :country, through: :state
  has_many :posts
end

class State
  belongs_to :country
  has_many :cities
  has_many :posts, through: :cities
end

class Country < ApplicationRecord
  has_many :states
  has_many :cities, through: :states
  has_many :posts, through: :cities
end

Polymorphic associations are a very different thing altogether - its used when an association can be to different models. In this example a Comment can be belong to a Post or a Page.
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

class Post < ApplicationRecord
  # this tells AR to look at the `commentable` association on
  # Comment.
  has_many :comments, as: :commentable
end

class Page < ApplicationRecord
  has_many :comments, as: :commentable
end


text:
Q: System.IO.FileNotFoundException: Could not load assembly...perhaps doesn't exist in the Mono for Android Profile? I am getting the following error when trying to compile my Android App from Visual Studio (I am using Xamarin plug in).

Error 2   Exception while loading assemblies: System.IO.FileNotFoundException: Could not load assembly 'PresentationUI, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'PresentationUI.dll'    at
Xamarin.Android.Tuner.DirectoryAssemblyResolver.Resolve(AssemblyNameReference
reference, ReaderParameters parameters)    at
Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(List`1
assemblies, AssemblyDefinition assembly, Boolean topLevel)    at
Xamarin.Android.Tasks.ResolveAssemblies.AddAssemblyReferences(List`1
assemblies, AssemblyDefinition assembly, Boolean topLevel)    at
Xamarin.Android.Tasks.ResolveAssemblies.Execute()

I had a look around and found this forum post which looks like a similar problem. I couldn't find the PresentationUI.dll assembly tho.
Any suggestion on why am I getting this error and how to fix it?
Update
I found that the problem actually comes from using DelegateCommand from Microsoft.Practices.Prism.dll
Is it because this assembly is not supported by Xamarin?
Cheers,

A: PresentationUI is part of WPF (UI framework on Windows), which is not available on mobile platforms, such as Xamarin.Android.
You have to recreate a mobile compatible UI of your application so as to be Android ready.
Microsoft designs Prism to work with WPF, so yes you cannot use it in a Xamarin.Android project. (Prism latest build does work with Xamarin Forms though).
Reference: .NET Cross Platform UI Frameworks

A: This exception means that in your mobile project somewhere in code you are using elements from PresentationUI that is WPF part and as mentioned above it can't be used in Xamarin.Android.
Just review your code and make sure that you aren't using something from PresentationUI.
Hope this will help.


text:
Q: RTK Query Interceptor Circular Dependency Trying to figure out the best way to achieve the following:

*

*API via createApi

*Auth slice via createSlice

*Clear the redux auth state when the API receives a 401.

No problem with the first 2! But the issue is when I need to add an interceptor to the API (invalid auth - clear the local auth state):
// api.ts
import authSlice from './authSlice';
const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = async (
  args,
  api,
  extraOptions
) => {
  const result = await baseQuery(args, api, extraOptions)

  if (result.error?.status === 401) {
    api.dispatch(authSlice.actions.clearAuth())
  }

  return result
}

export const api = createApi({
  reducerPath: API_REDUCER_KEY,
  baseQuery: baseQueryWithReauth,
  endpoints: () => ({}),
})

// authService.ts
import { User } from '../../models/User'
import { api } from '../api'

export const API_REDUCER_KEY = 'api'

interface AuthResponse {
  user: User
  jwt: string
}

interface LoginData {
  email: string
  password: string
}

export const authApi = api.injectEndpoints({
  endpoints: (builder) => ({
    login: builder.mutation<AuthResponse, LoginData>({
      query: (body) => {
        return {
          url: 'login',
          method: 'POST',
          body,
        }
      },
    }),
  }),
})

export const { useLoginMutation } = authApi

This causes a circular dependency - as the auth slice needs to call the API for the auth functions (login, logout, etc.):
// authSlice.ts
import { api } from './api';
...
export const loginLocal = createAsyncThunk<
  Pick<AuthState, 'user' | 'accessToken'>,
  {
    email: string
    password: string
  }
>('auth/login', async ({ email, password }, { dispatch }) => {
  const response = await dispatch(
    authApi.endpoints.login.initiate({
      email,
      password,
    })
  )

  if ('error' in response) {
    if ('status' in response.error) {
      throw new Error(response.error.data as string)
    }
    throw new Error(response.error.message)
  }

  const { data } = response

  const { jwt: accessToken, user } = data

  return { user, accessToken }
})

The circular dependency is as follows: authSlice -> authService -> api -> authSlice
Is there a way around this - or is there a better/different pattern I can use?

A: An easy solution was to simply pull the "clearAuth" action into it's own file - as per https://redux-toolkit.js.org/usage/usage-guide#exporting-and-using-slices:

This will usually require extracting shared code to a separate common file that both modules can import and use. In this case, you might define some common action types in a separate file using createAction, import those action creators into each slice file, and handle them using the extraReducers argument.

// clearAuthAction.ts
import { createAction } from '@reduxjs/toolkit'

export const CLEAR_AUTH = 'auth/clearAuth'

export const clearAuth = createAction<void>(CLEAR_AUTH)

Then use the builder in authSlice:
// authSlice.ts
builder.addCase(CLEAR_AUTH, (state) => {
  state.user = null
  state.accessToken = null
})

And dispatch clearAuth in the API:
// api.ts
const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = async (
  args,
  api,
  extraOptions
) => {
  const result = await baseQuery(args, api, extraOptions)

  if (result.error?.status === 401 || result.error?.status === 403) {
    api.dispatch(clearAuth())
  }

  return result
}


text:
Q: Sci-fi book about man who built an interstellar ship with the use of a collider and met his enemy inside of the Sun The main character of the book finds out that he built an interstellar ship with the use of a collider and then removed his memory to refuse from interstellar travel. He also had a suit built with the use of a collider. Both could resist any heat, even inside of the Sun.
Throughout the story, he tries to find his enemy, but can't, and at the end he goes inside of the Sun to avoid any external interference and realises that his enemy is very tiny and had been on his ship all along.
I think the name of this book is the name of the ship, but I can't remember it.
I read this book about 15 years ago. I used electronic version so don't know how cover looked like.
I assume it was published in 1980-1990s.

A: This sounds like John C. Wright's Golden Oecumene series.
The main character of the book finds out that he built an interstellar ship with the use of a collider and then removed his memory to refuse from interstellar travel. He also had a suit built with the use of a collider. Both could resist any heat, even inside of the Sun.
From this review

That man is Phaethon, an engineer and visionary who, as The Golden Age
begins, discovers that he has recently entered into an agreement to
wipe most of the last two hundred and fifty years of his life from his
memory. His attempts to find out why he agreed to have his memory
erased and whether he should seek to regain his memories form the
narrative structure of the story.

From the book itself:

The expense of this suit was staggering. The material was rare; only
the supercollider that orbited the equator of Jupiter could generate
sufficient energy to create the artificial atoms, and even that
required a major percentage of the output of the small star that
Gannis had made by igniting Jupiter. This suit had been constructed
one atom at a time. The black material, now inside the suit, was
cyclic nano-machinery, which would form a self-contained and
selfsustaining symbiosis with the wearer: a miniature and complete
ecosystem. But what in the world was it for? Swimming among the
granules of the sun? Walking into the core chambers of plasma
reactors?

I think the name of this book is the name of the ship, but I can't remember it.
The second book in the series is The Phoenix Exultant which is the name of Phaeton's ship.


text:
Q: Wordpress Help: Make first post full text, the rest excerpts I'm trying to make my WP theme show the full text of the first post, and just excerpts for the remaining posts on the homepage. When I implement the below, it shows all posts as excerpts, including the first post.
Here's the code for index.php...
 $some_number = 0;
 if (have_posts()) : while (have_posts()) : the_post();
 $some_number++;

Here is the code for post-homepage.php...
<p>
<?php
    global $some_number;
    if($some_number == 1) {
        the_content(); }
    else {
        the_excerpt();
    }
 ?>
 </p>

Any ideas why this wouldn't do the trick?

A: You are initializing $some_number within the loop. Just move it before the loop:
$some_number = 0;
if (have_posts()) : while (have_posts()) : the_post();
     $some_number++;

Otherwise, it will reset the variable for each post.


text:
Q: Alternatives to VBScript for running scheduled tasks We inherited a bunch of legacy (10+ years old) VBScript files which use to run on a schedule using Windows task manager.
As part of the infrastructure upgrade we are finding out that old 3rd party (Server Objects) components which the scripts reply on no longer work on Win7 / IIS 7.
So as part of this upgrade effort we are considering re-writing these scripts so they don't reply on 3rd party components.
The core of these "scripts" will be a a bunch of HTTP requests running on a scheduled task.
We plan to replace these scripts with C# console programs.  But before doing so would like to check with the community to check if there are any better alternatives?
High level requirement is to run under a schedule task to make a HTTP requests (passing basic windows authentication) and with access to the local file system to write logs etc.
Does Windows Powershell cut it?

A: I would try PowerShell.
Here is an short example from Scott Hanselman blog about downloading all his podcasts with PowerShell script.


text:
Q: Adding Box plot below x axis I have the code below and was wondering if there's a way to have the box plot below the the x-axis or another package. Or have the box plot below the x-axis in general with a white background. Thanks!
library(ggstance)
library(ggplot2)

ggplot(diamonds, aes(x = carat, y = -0.5)) +

  # horizontal box plot
  geom_boxploth(aes(fill = cut)) +

  # normal density plot
  geom_density(aes(x = carat), inherit.aes = FALSE) +

  # reproduce original chart's color scale (o/w ordered factors will result
  # in viridis scale by default, using the current version of ggplot2)
  scale_fill_discrete()

A: You could use the patchwork package:
library(patchwork)

 p <- ggplot(diamonds, aes(x = carat, y = -0.5))

 p1 <- p + geom_density(aes(x = carat), inherit.aes = FALSE)
 p2 <- p + geom_boxploth(aes(fill = cut)) +
       theme_classic() +
       theme(axis.text = element_text(color = 'white'),
             axis.title = element_blank(),
             axis.line = element_blank(),
             axis.ticks = element_blank())
 p1/p2 + plot_layout(ncol = 1, nrow = 2, heights = c(2, 1),
                     guides = 'collect')


text:
Q: Run watcher fsinotify to watch configuration file changing | GO I am trying to run a watcher in go using fsinotfiy lib to follow configuration json file changes - use this code
func waitForChangeEventLoop(w *fsnotify.Watcher) (error) {
    for {
        select {
        // Read from Errors.
        case _, ok := <-w.Errors:
            if !ok {
                // Channel was closed (i.e. Watcher.Close() was called).
                return nil
            }
        // Read from Events.
        case e, ok := <-w.Events:
            if !ok {
                // Channel was closed (i.e. Watcher.Close() was called).
                return nil
            }

            if e.Has(fsnotify.Write) {
                fmt.Println("Something happen")
            }
        }
    }

    return nil
}

func setFileWatcher() (error) {
    w, err := fsnotify.NewWatcher()
    if err != nil {
        return err
    }

    go waitForChangeEventLoop(w)

    err = w.Add(gConfiguredCollectorsPath)
    if err != nil {
        return err
    }

    defer w.Close()

    return nil
}

I am expecting to get notes during the process is running, any time I change the json file

A: Something like this should work. Just doing it in main for keeping it simple but moving away in a separate method like you do should work too.
package main

import (
    "log"

    "github.com/fsnotify/fsnotify"
)

func main() {
    // Creating a new watcher
    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        log.Fatalf("Failed to create watcher: %v", err)
    }

    //Defer close the watcher
    defer watcher.Close()

    // Adding some sample config file
    err = watcher.Add("config.json")
    if err != nil {
        log.Fatalf("Failed to add file to watcher: %v", err)
    }

    // Let's start the event loop
    for {
        select {
        case event := <-watcher.Events:
            // Checks for any modification in config file
            if event.Op&fsnotify.Write == fsnotify.Write {
                log.Println("Configuration file changed, reloading...")

            }
        case err := <-watcher.Errors:
            log.Printf("Watcher error: %v", err)
        }
    }
}


text:
Q: ROLLBACK undo redo I'm building a database using a BST (binary search tree) and I want the user to be able to roll back the last 5 commands. Any Suggestions? I'm using Java.

A: Have you considered using Berkey DB? It's free and supported nested transactions (which would allow you to have any number of levels of rollback):
http://download.oracle.com/docs/cd/E17076_02/html/gsg_txn/JAVA/nestedtxn.html
Even if you decide to implement your own DB, it might be useful as a reference.

A: It sounds like you want the Memento pattern.  Essentially, you create an object that has all of the information required to:

*

*From the state of the tree before the operation, repeat the operation. (Redo)

*From the state of the tree after the operation, revert the operation. (Undo)

You'd keep the last five of these around.  When the user asks for an undo, take the latest, ask it to revert the operation, then indicate somehow (some index variable, for example) where you are in the list of mementos.  You should then be able to move through the list in either direction, undoing and redoing as much as you want.


text:
Q: Issue with div functionaility if content is served via JQuery and not hardcoded My problem is probably easiest explained from this fiddle: http://jsfiddle.net/L3zVY/7/
If you click the image in the top right of the box, the boxes fade away (image isn't present so it's just a question mark).
If I try and dynamically manipulate these boxes instead of them being hardcoded then this functionality is lost for some reason.
The reason I am doing it this way is because I have a login page using a box that changes class depending on the error message. Everything works fine except for being able to close the box...
Any ideas?
Code:
$(document).ready(function() {
// Close notifications (fade and slideup)

        $(".notification a.close").click(function () {
            $(this).parent().fadeTo(400, 0, function () {
                $(this).slideUp(200);
            });
            return false;
        });

// JQuery Broken Notification:
    $("#msgbox1").html('Broken :( ');

});

A: When you assign the click handler, the element you insert does not exist yet, hence jQuery cannot find it.
Either insert the element first:
$(document).ready(function() {
    $("#msgbox1").html('...');
    $(".notification a.close").click(...);
});

or use .live() / .delegate():
$(document).ready(function() {
    $(".notification").delegate('a.close', 'click', function(){...});
    $("#msgbox1").html('...');
});

Event handlers are always bound to the element. You cannot bind anything to something that does not exist. live/ delegate overcome this problem by binding an event handler further up the DOM tree (possible because of event bubbling) and checking the target of the event.

A: http://jsfiddle.net/L3zVY/8/  You need to use the live() function with jquery.


text:
Q: What is the effect of using np.dot on two vectors? This problem is to do with the numpy library.
From previous experience np.dot is the same as matrix multiplication. However I was under the assumption that multiplying two vectors is impossible as the dimensionality is wrong. So my question is, what does np.dot actually do to two vectors?
Furthermore, say I had the following code and assuming np.dot produces a scalar (as it says on the documentation).
x= np.dot(dc, self.c)[:self.ys]

where x is also a vector, how does the operation [:self.ys] change the result of the two vectors in an np.dot into a vector? I cannot find anything detailing on this.

A: numpy.dot performs a "dot" or inner product between two products. However, it also performs an operation called broadcasting that is common to many languages (except matlab rebrands the dimension matching part as implicit expansion). In this case the dimensions are completed to a matching product automatically for convenience and performance. More explanation is here.
[:self.ys] is a slice. Suppose the value of self.ys is 5. Then it means take the result of the dot product and only assign the first 5 items to x since Python uses zero indexing. You can omit the starting number if it is zero hence it is also for convenience. [a:b] is [a,a+1,...,b-1] if a is 0 then you can leave it out and it is assumed.

A: numpy.dot() function returns the dot product of two arrays. For 2-D vectors, it is the equivalent to matrix multiplication. For 1-D arrays, it is the inner product of the vectors. For Ndimensional arrays, it is a sum product over the last axis of a and the second-last axis of b.
Source: https://www.tutorialspoint.com/numpy/numpy_dot.htm


text:
Q: Error Message : Index was outside the bounds of the array I'm aware of what the issue is stating but I am confused to how my program is making this error.
I have two arrays of strings in a dll file:
string[] Names = { };
string[] SignalQuality = { };

The code that I set again the strings[] inside the class:
Names[i] = networkName;
SignalQuality[i] = network.wlanSignalQuality + "%";

And when I call them from my program using Tuple:
string[] Names = Network.GetAvailableRouters().Item1;
string[] Signals = Network.GetAvailableRouters().Item2;
Console.WriteLine(Names[0] + " " + Signals[0]);

Throws me an exception message inside the class:

System.IndexOutOfRangeException: 'Index was outside the bounds of the
  array.'

Full Code:
public static Tuple<string[], string[]> GetAvailableRouters()
{
    //Declare here as I said
    string[] Names = { };
    string[] SignalQuality = { };
    WlanClient client = new WlanClient();

    foreach (WlanClient.WlanInterface wlaninterface in client.Interfaces)
    {
        Wlan.WlanAvailableNetwork[] networks = wlaninterface.GetAvailableNetworkList(0);
        foreach (Wlan.WlanAvailableNetwork network in networks)
        {
            int i = 0;
            Wlan.Dot11Ssid ssid = network.dot11Ssid;
            string networkName = Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
            Names[i] = networkName;
            SignalQuality[i] = network.wlanSignalQuality + "%";
            i++;

        }
    }
    //return with Tuple.Create()
    return Tuple.Create(Names, SignalQuality);
}

A: The arrays have fixed size length and since you didn't initialized them, and because you don't know the number of items you probably should use a generic List instead. Lists are dynamically resizable, arrays are not:
List<string> Names = new List<string>();
Names.Add(networkName);

A: Firstly your code will perform poorly if you are calling Network.GetAvailableRouters() twice. Put that into a variable like var availableRouters then access availableRouters.Item1 and availableRouters.Item2 respectively.
Secondly you seem to require building a collection of items with an unknown length (because you are using a foreach not a for), so string[] is not what you want which requires a predetermined number of items in your array.
Try using a generic list of strings (i.e. var names = new List<string>();) and call it's add function like so names.Add(networkName) to build your collection.
It is essentially a string array with added features to allow you to add to a "perceived" unbounded collection.


text:
Q: Totally bizzare: deleting a MySQL user allows me to still login as that user with an empty password Using MySQL 5.5 on Arch Linux, when I create a localhost user with a password and give it all privileges to all tables and then delete that user, I can still login as that user without typing in a password.
Steps to reproduce:
# mysql -u root -h localhost -p
  Enter password: <root password>

mysql> create user 'test'@'localhost' identified by 'testing123';
mysql> grant all on *.* to 'test'@'localhost' identified by 'testing123';
mysql> select * from mysql.user where user='test';
       1 row in set (0.00 sec)
mysql> exit

# mysql -u test -h localhost -p
  Enter password: testing123

mysql> show databases;
mysql> exit

# mysql -u root -h localhost -p
  Enter password: <root password>

mysql> delete from mysql.user where user='test';
       Query OK, 1 row affected (0.00 sec)
mysql> FLUSH PRIVILEGES;
mysql> select * from mysql.user where user='test';
       Empty set (0.00 sec)
mysql> exit

# mysql -u test -h localhost

mysql> (Why?)

Not only that, but the "non-existing" test user can still exercise all of the same privileges. Major security problem. If I restart the server, it still lets me login without a password.

A: I finally figured out what was happening. By default, in the user table there is an anonymous user @ localhost. This user is automatically matched with any attempted username and logged in as that anonymous user. Kind of strange, I know. To get rid of the anonymous user, login as root and perform the following command:
drop user ''@localhost;


text:
Q: NullInjectorError: No provider for AddItemPage! -- Ionic 3 Error:

Error: Uncaught (in promise): Error: StaticInjectorError[AddItemPage]:
  StaticInjectorError[AddItemPage]:
      NullInjectorError: No provider for AddItemPage! Error: StaticInjectorError[AddItemPage]:    StaticInjectorError[AddItemPage]:
NullInjectorError: No provider for AddItemPage!
at _NullInjector.get (http://localhost:8100/build/vendor.js:1276:19)
at resolveToken (http://localhost:8100/build/vendor.js:1564:24)
at tryResolveToken (http://localhost:8100/build/vendor.js:1506:16)
at StaticInjector.get (http://localhost:8100/build/vendor.js:1377:20)
at resolveToken (http://localhost:8100/build/vendor.js:1564:24)
at tryResolveToken (http://localhost:8100/build/vendor.js:1506:16)
at StaticInjector.get (http://localhost:8100/build/vendor.js:1377:20)
at resolveNgModuleDep (http://localhost:8100/build/vendor.js:10938:25)
at NgModuleRef_.get (http://localhost:8100/build/vendor.js:12159:16)
at resolveNgModuleDep (http://localhost:8100/build/vendor.js:10938:25)
at c (http://localhost:8100/build/polyfills.js:3:19752)
at Object.reject (http://localhost:8100/build/polyfills.js:3:19174)
at NavControllerBase._fireError (http://localhost:8100/build/vendor.js:48310:16)
at NavControllerBase._failed (http://localhost:8100/build/vendor.js:48303:14)
at http://localhost:8100/build/vendor.js:48350:59
at t.invoke (http://localhost:8100/build/polyfills.js:3:14976)
at Object.onInvoke (http://localhost:8100/build/vendor.js:4982:33)
at t.invoke (http://localhost:8100/build/polyfills.js:3:14916)
at r.run (http://localhost:8100/build/polyfills.js:3:10143)
at http://localhost:8100/build/polyfills.js:3:20242

When I write in HomePage:
import { AddItemPage } from './../add-item/add-item';
...
constructor(... ,private addItemPage: AddItemPage){...}
...
editItems(item){
    this.addItemPage.editItem(item);
}

So I want to call a methode from AddItemPage in HomePage.
Any Solutions?

A: Add import to app.module.ts
...
import { AddItemPage } from '../add-item/add-item';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    AddItemPage
  ],
...

A: You're calling AddItemPage like a provider. So if AddItemPage is a page, you need to import it into app.module.ts declaration array.
Then, you want to call a method from AddItemPage in HomePage. To get access to a component and its methods, you can use the @ViewChild decorator.
export class AddItemPage {
  constructor() {}
  doSomething() {
    //send data
  }
}

import { Component, ViewChild } from '@angular/core';
import { AddItemPage } from '../add-item';

export class HomePage {
  // ViewChild takes a class type or a reference name string.
  // Here we are using the type
  @ViewChild(AddItemPage) addItemPage: AddItemPage

  constructor() { }

  update() {
    this.addItemPage.doSomething();
  }
}

I do not know what the goal is, but I think you can do it differently.
Hope I help!


text:
Q: How do I convert 'Month(String) YYYY' to 'YYYY-MM-DD' in Pandas? I have data like
|   |Period         | Total
--------------------------------
|0  |January 2000   |49045412
|1  |February 2000  |49306303
|2  |March 2000     |60443541
|3  |April 2000     |58286680
|4  |May 2000       |60533783

To convert Period column to the desired output, I tried valid conversion which should work
time['Month'] = pd.to_datetime(df['Period'])

It's working for most of the month's but failing for few as shown below
|   |Period         | Total     |Month
-----------------------------------------
0   |January 2000   |49045412   |2000-01-01
1   |February 2000  |49306303   |2000-02-01
2   |March 2000     |60443541   |2000-03-01
3   |April 2000     |58286680   |2000-04-01
4   |May 2000       |60533783   |2000-05-01
5   |June 2000      |64903295   |NaT
6   |July 2000      |67346377   |NaT
7   |August 2000    |66256804   |NaT
8   |September 2000 |55900504   |NaT
9   |October 2000   |58373996   |NaT
10  |November 2000  |55590325   |NaT
11  |December 2000  |54822970   |NaT

A: What you tried works for me, more specific one could be using format arg of to_datetime.
df['Month'] = pd.to_datetime(df.Period, format='%B %Y')

Output
    Period          Total       Month
0   January 2000    49045412    2000-01-01
1   February 2000   49306303    2000-02-01
2   March 2000      60443541    2000-03-01
3   April 2000      58286680    2000-04-01
4   May 2000        60533783    2000-05-01
5   June 2000       64903295    2000-06-01
6   July 2000       67346377    2000-07-01
7   August 2000     66256804    2000-08-01
8   September 2000  55900504    2000-09-01
9   October 2000    58373996    2000-10-01
10  November 2000   55590325    2000-11-01
11  December 2000   54822970    2000-12-01

A: d = ['September 2021', 'September 2000', 'April 2000']
df = pd.DataFrame({'period': d})

before:
    period
0   September 2021
1   September 2000
2   April 2000

the fix:
df.period = pd.DatetimeIndex(df.period)

after:
    period
0   2021-09-01
1   2000-09-01
2   2000-04-01


text:
Q: Whether DDL Commands on Child Table will affect its Parent Table in MySQL? In MySQL (5.5) that uses innoDB storage engine, if a column is added/deleted in a child table (that column is not a foreign key reference to the parent table) will it affect the parent table as well? If so, how and if not, why?
Example:
Parent Table: Vehicle
Child Table: Car
Assume that Car has some Columns, (say, vehicle_id, car_type) where vehicle_id references Vehicle.
Now, if I add a new Column in Car Table (say car_driver), will it affect the parent table Vehicle in any manner (SELECTs, INSERTs, UPDATEs or DELETEs)?
Both the tables will have at-least 10 Million rows.
(When we had such a scenario, there were some select queries to the parent table while we executed SHOW FULL PROCESSLIST) and we were sure that no external queries were fired on parent table)


text:
Q: calculated property in Django model with QuerySet I am working on a frontend that consumes a Django backend.
I want to add a new calculated property to one Django model, that contains chart-data for amCharts.
After some research i found out, that using @property would be the way to go here.
However all the viewsets implemented atm use querysets, which as i found out after some googling ignore calculated properties.

*

*Is there a way to keep the queryset and let it use my calculated property?

*If not: Would manually writing out all the queryset operations solve the problem?

Code:
# models.py
class MyModel:
    # Normal props

    @property
    def calced(self):
        return somecalc

# views.py
class MyModelView(ModelViewSet):
    serializer_class = MyModelSerializer

    def get_queryset(self):
        return MyModel.objects.filter(id=self.kwargs['id_pk'])

A: As suggested by @dirkgroten i used the SerializerMethodField to add the new json-field before django ships my result.


text:
Q: Find elapsed time of sidekiq job Is there an easy method to see the elapsed time of a sidekiq job?

A: The log output?
ScheduledWorker JID-072f6c37f240a92ca3c07914 INFO: start
ScheduledWorker JID-072f6c37f240a92ca3c07914 INFO: done: 0.003 sec


text:
Q: Sort in subtitle for TableViewCell I am having trouble using the sortDescriptors to sort out the UITableViewCell.  I don't get any errors but it is not working.  I know that I am missing on how to add the sort to the cell.
Any help is appreciated.  thanks
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell {

// Configure the cell...

    let fetchRequest = NSFetchRequest(entityName: "List")
    let divenumberSort = NSSortDescriptor(key:"divenumber", ascending: true)
    fetchRequest.sortDescriptors = [divenumberSort]

    let CellID: NSString = "Cell"
    var cell: UITableViewCell = tableView?.dequeueReusableCellWithIdentifier(CellID as String)! as! UITableViewCell

    if let ip = indexPath{

        var data: NSManagedObject = myList[ip.row] as! NSManagedObject
        var divelocation = data.valueForKeyPath("divelocation") as! String
        var divenumber = data.valueForKeyPath("divenumber") as! String
        cell.textLabel!.text = "#\(divenumber)" + "  @ \(divelocation)"

        var ddate = data.valueForKeyPath("divedate") as! String
        var dnumber = data.valueForKeyPath("divenumber") as! String

        cell.detailTextLabel!.text = "\(dnumber) date: \(ddate)"
    }
    return cell
}

A: Did you try to sort the list before setting the dataSource?
 list.sort({ $0.valueForKeyPath("divenumber") > $1.valueForKeyPath("divenumber") })


text:
Q: Android app built using Xamarin does not show up on emulator I have written a simple login page using xamarin forms. When I try to deploy it on emulator, the emulator opens but my app is not visible.
1) Does it take time for the app to be deployed? Or would it appear on start up?
2) Should warnings be considered? I have no errors though.

A: Most Android emulated devices are slow. I have found that some of them simply won't render an app. This is not an indication that the physical device, which you are trying to emulate, won't work however. Try testing what works in an emulator and then creating a copy of what works in the device manager. Then make slight changes that are closer to the target device in the copy. Deploy every time to ensure that it is working. This process takes patience.  If you are fortunate enough to have the physical device, debug through the USB connection.


text:
Q: How to access a node properties on neo4j unmanaged extension i m new in neo4j and unmanaged extension.
i just write HelloWorld example in neo4j and the code is the following
//START SNIPPET: HelloWorldResource
@Path( "/helloworld" )
public class HelloWorldResource
{
    private final GraphDatabaseService database;

    public HelloWorldResource( @Context GraphDatabaseService database )
    {
        this.database = database;
    }

    @GET
    @Produces( MediaType.TEXT_PLAIN )
    @Path( "/{nodeId}" )
    public Response hello( @PathParam( "nodeId" ) long nodeId )
    {
        // Do stuff with the database

        return Response.status( Status.OK ).entity(
                ("Hello World2, nodeId=" + nodeId + ", ADDRESSNO = " +     "").getBytes( Charset.forName("UTF-8") ) ).build();
    }
}

how can i access to the node its id is nodeId
how can i access its address property

A: inside the hello method:
try (Transaction tx = database.beginTx()) {
    Node n = database.getNodeById(nodeId);
    String address = (String)n.getProperty("address", null);

    tx.success();
}


text:
Q: How to send data to json file using jquery/ajax I have found countless tutorials on how to retrieve data from json files using jQuery and ajax but none on how to POST data to a json file. If some one could show me or send me a small script on how to do this that would be great. I have searched everywhere on how to do this and have had no luck. I have seen examples of people doing it but they seem to forget to share important info that i am not seeing.I have no problem retrieving data json files using ajax.
If someone could tell me if i am forgetting something or doing something wrong that would be great.
I would be very appreciative if someone could send me a working file so that i can reverse engineer ir and understand how to do it.
I am wanting to send the values from $firstName and $caption to the json file.
I know this may seem stupid to others but i am tired of all the searching and not getting any straight answers.
Here is what i have.
      getImages: function(){
        var $firstName = $(".name"),
            $caption = $(".caption");
        var object = {
            name: $firstName.val(),
            caption: $caption.val()
        }
        $.ajax({
            type: 'POST',
            data: object,
            url: 'images.json',
            success: function(data){
                console.log("KILLER");
                var count = 0;
                $.each(data, function(i, imgSlide){
                    count ++;
                    //console.log(result.sliderImages[i].url[0].thumb);
                    var imageEl = "";
                    var slide = "
"+imageEl+"
";
                    $("ul.imageGallery").append(slide).fadeIn();
                });
            },
            error: function(){
                console.log("Abort");
            },
            timeout: 3000,
            beforeSend: function(){

            },
            complete: function(){

            }
        });

    }

and here is my JSON file
    [{
      "name": "Bootcamp",
      "url": [{
        "thumb": "img/ill-bootcamp.jpg",
        "med": "img/ill-bootcamp.jpg",
        "large": "img/ill-bootcamp.jpg"
            }],
      "caption": "Lifetime Fitness",
      "ID": ""
     },
     {
       "name": "Pinup Girl",
       "url": [{
            "thumb": "img/ill-pinup.jpg",
            "med": "img/ill-pinup.jpg",
            "large": "img/ill-pinup.jpg"
             }],
      "caption": "Illustration",
      "ID": ""
     },
     {
       "name": "SixDitch",
       "url": [{
             "thumb": "img/web-sixditch.jpg",
             "med": "img/web-sixditch.jpg",
             "large": "img/web-sixditch.jpg"
             }],
       "caption": "SD MotorSports",
       "ID": ""
     }]

A: So you will need to use server-side script language. In this case we will use PHP.
After defining your json object you turn it into string and send it to the php file via post. From there the PHP will take it and encode it as a JSON object. This json object will saved to a file named my_json_data.json with the php function file_put_contents(). If you want to append the new content instead of replacing the old one use the function like this:
file_put_content('my_json_data.json', $jsonObject, FILE_APPEND);

JavaSrcipt:
var $firstName = $(".name"),
    $caption = $(".caption");
var object = {
    name: $firstName.val(),
    caption: $caption.val()
}

var params = JSON.stringify(object);

$.ajax({
    type: 'POST',
    data: params,
    url: 'save_to_json.php',
    success: function(data){
        // do something on success
    },
    error: function(){
        // do something on error
    }
});

PHP (save_to_json.php):
    if (!isset($_POST['params']) && !empty($_POST['params'])) {
        $params = $_POST['params'];

        $jsonObject = json_encode($params);
        file_put_contents('my_json_data.json', $jsonObject);
    }

I hope I didn't missed something. Good luck.

A: It was a bit unclear ...
client side languages are not able to write or edit something on the server
via AJAX (with or without jQuery) you are only able to read data or send them

so you can pass your data to a php file then execute what you want to do ,  by php.
here is a tutorial for working with files in php http://www.w3schools.com/php/php_file_open.asp
and here is another one for getting passed data by AJAX in php file
http://www.w3schools.com/php/php_superglobals.asp

look at $_GET , $_POST , $_REQUEST

good luck


text:
Q: How do I uninstall Visual Studio 2012 Update 2? I installed VS2012 and then I updated to VS2012 Update 2, so my Visual Studio version would be 11.0.60315.01 Update 2.
But now I want to revert to 11.0.50727.1 RTMREL. How can I uninstall the update?

A: Updates to Visual Studio are implemented as Windows updates, much like Office and other Microsoft suites. Once you know this, it immediately becomes obvious where to look. (Of course, the difficult part is knowing in the first place...)
You can find the update by visiting the Programs control panel category, and choosing View installed updates under the Programs and Features subcategory:

Alternatively, from the Windows Update control panel, choose View update history in the task pane, then click Installed Updates in the update history page.
Either option takes you to the same list of updates; most VS2012 updates should be listed under the Microsoft Visual Studio 2012 update category.


text:
Q: How to Configure BonitaBPM Platform for BonitaBPMCommunity Tomcat Bundle I have tried simple process variable example given at link http://community.bonitasoft.com/project/process-variable-example using BonitaBPMCommunity-7.3.1-Tomcat-7.0.67. Its working well in bonita studio and with default h2 database configuration with tomcat bundle. But when i configure tomcat bundle with PostgreSQL database its not working well with Bonita ui forms but working well with process containing 6.x forms. I have followed database configuration instructions given at official link http://documentation.bonitasoft.com/?page=tomcat-bundle . There is no error in log file at the time of PostgresSQL configuration with bundle. This behavior is because of reason that i am running tomcat bundle "BonitaBPMCommunity-7.3.1-Tomcat-7.0.67" on Windows 7 Ultimate 32 bit? I am new to Bonita kindly forgive if i have asked something stupid.
Error (when i run process in Mozilla Firefox developer mode):
myProcessVariable is a Process Variable defined in process.

http://localhost:8888/bonita/portal/resource/taskInstance/ProcessVariabl... [HTTP/1.1 403 Forbidden 0ms]
no element found
In Log file i got error when i submit Instantiation form.
Error evaluating < formOutput > data: $data.processVariableValue is undefinedvendor.min.js:105:441
GET
XHR

My Log File:
016-12-01 03:11:47.497 -0800 INFO: org.bonitasoft.platform.setup.PlatformSetup System property org.bonitasoft.platform.setup.folder is set to C:\BonitaBPM\BonitaBPMCommunity-7.3.1-Tomcat-7.0.67\setup
2016-12-01 03:11:47.541 -0800 INFO: org.bonitasoft.platform.setup.PlatformSetup Connected to 'h2' database with url: 'jdbc:h2:tcp://localhost:9091/bonita_journal.db' with user: 'SA'
2016-12-01 03:11:47.545 -0800 INFO: org.bonitasoft.platform.setup.ScriptExecutor configuration for Database vendor: h2
2016-12-01 03:11:47.757 -0800 INFO: org.bonitasoft.platform.setup.PlatformSetup Platform is already created. Nothing to do.
2016-12-01 03:11:47.866 -0800 INFO: org.bonitasoft.engine.EngineInitializer Initializing Bonita Engine...
2016-12-01 03:11:47.866 -0800 INFO: org.bonitasoft.engine.EngineInitializer Initializing Spring context...
2016-12-01 03:11:58.510 -0800 WARNING: org.hibernate.type.TypeFactory HHH000233: Scoping types to session factory org.hibernate.internal.SessionFactoryImpl@ac6f04 after already scoped org.hibernate.internal.SessionFactoryImpl@ac8478
2016-12-01 03:12:02.630 -0800 INFO: org.bonitasoft.engine.EngineInitializer Starting platform...
2016-12-01 03:12:10.080 -0800 INFO: org.bonitasoft.engine.EngineInitializer Platform started successfully
2016-12-01 03:12:10.081 -0800 INFO: org.bonitasoft.engine.EngineInitializer Initialization of Bonita Engine done! ( took 22215ms)
2016-12-01 03:13:41.877 -0800 INFO: org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/bonita] RestletServlet: [Restlet] ServerServlet: component class is null
2016-12-01 03:13:42.396 -0800 INFO: org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/bonita] RestletServlet: [Restlet] Attaching application: org.bonitasoft.web.rest.server.BonitaRestletApplication@1b811b to URI: /bonita/API
2016-12-01 03:13:42.412 -0800 INFO: org.restlet.Component.BonitaRestletApplication Starting org.bonitasoft.web.rest.server.BonitaRestletApplication application
2016-12-01 03:15:43.466 -0800 INFO: org.restlet.Component.BonitaRestletApplication Error while validating expected inputs
Explanations:
Expected input [newVariableValue] is missing

A: In the instantiation form of the "Process variable example" there is no processVariableValue variable. The only variable defined in the instantiation form is named formOutput. When submit button is clicked the formOutput value is sent (see "Data sent on click" property of the button).
So my guess is maybe you edit the form and change the definition of the formOutput variable to a JavaScript type and add a reference to a variable named processVariableValue that does not exist in the form.
I would recommend to import again the example in the Studio, regenerate the .bar file and try to deploy it again.


text:
Q: The service APIs should not be bundled with the implementations.; creating "Ghost" implementation I am working on the following Nifi controller service bundle:

*

*nifi-controllers-bundle

*

*nifi-controllers

*nifi-controllers-api

*nifi-controllers-nar

*nifi-controllers-api-nar

I have a custom controller service created(StandardMyService) that extends DBCPConnectionPool in the nifi-controllers module and when I try to use it in UI I get the following exception in logs: ERROR [NiFi Web Server-36] o.a.nifi.controller.ExtensionBuilder Could not create Controller Service of type com.xxx.yyy.StandardMyService for ID 812de259-0181-1000-3536-a06e3ae9f2ed due to: Controller Service com.xxx.yyy.StandardMyService is bundled with its supporting APIs org.apache.nifi.dbcp.DBCPService. The service APIs should not be bundled with the implementations.; creating "Ghost" implementation and this one in UI: 'Missing Controller Service' validated angainst 'Any property' is invalid because controller service is of type com.xxx.yyy.StandardMyService but this is not a valid Reporting Task Type
I do not think there is something wrong with the way I have implemented the StandardMyService class because I have tested it in a nifi controller service maven archetype and it works.
My nifi-controllers build.gradle looks like this:
dependencies {
    implementation group: 'com.oracle.ojdbc', name: 'ojdbc8', version: '19.3.0.0'
    implementation group: 'org.apache.nifi', name: 'nifi-nar-bundles', version: '1.12.0', ext: 'pom'
    compileOnly group: 'org.apache.nifi', name: 'nifi-api', version: '1.16.1'
    implementation group: 'org.apache.nifi', name: 'nifi-utils', version: '1.16.1'
    compileOnly group: 'org.apache.nifi', name: 'nifi-dbcp-service-api', version: '1.16.1'
    implementation group: 'org.apache.nifi', name: 'nifi-dbcp-service-nar', version: '1.16.1'
    compileOnly group: 'org.apache.nifi', name: 'nifi-dbcp-service', version: '1.16.1'
    testImplementation group: 'org.apache.nifi', name: 'nifi-mock', version: '1.16.1'
    testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.36'
    testImplementation group: 'junit', name: 'junit', version: '4.13.2'
    implementation group: 'com.fasterxml', name: 'aalto-xml', version: '1.3.2'
}
tasks.named('test') {
    useJUnitPlatform()
}

A: I got it to work by extending AbstractControllerService instead of DBCPConnectionPool, therefore not needing org.apache.nifi.dbcp.DBCPService anymore.
LE: Having the project built with gradle, there is no
<type>nar</type>

for nifi-standard-services-api-nar that puts this dependency in the MANIFEST file of the nar archive of processors-nar. When I added manually these lines in MANIFEST file, everything worked:
Nar-Dependency-Id: nifi-standard-services-api-nar
Nar-Dependency-Group: org.apache.nifi

and the only dependency needed in the project is nifi-dbcp-service-api in processors build.gradle.


text:
Q: Prove that if $A$ is an invertible $n × n$ matrix, then the columns of $A$ span $\mathbb R^n$ Prove that if $A$ is an invertible $n × n$ matrix, then the columns of $A$ span $\mathbb R^n$
How would I go about proving this?
So far my answer is like this but it's not sufficient enough apparently:

If $A$ is invertible that means its determinant does not equal $0$. This means the rows equals the number of columns. And so the row rank${}={}$column rank${}= n.$ So column spans all of $A$

How can I improve my explanation? Would it be better if I showed an example? Or would that not be considered a proof?

A: Your argument is basically good, though the half sentence 'This means the rows equals the number of columns' doesn't contain new information, as the matrix was assumed to be square.
The key connection you stated is that invertibility implies full rank.
For a direct approach, observe that for any $v\in\Bbb R^n$, the vector $Av$ is a linear combination of the columns of $A$.
Now if $A$ is invertible, then for any vector $w\in\Bbb R^n$ we have $Av=w$ where $v=A^{-1}w$.
So, every vector is in the column space of $A$.


text:
Q: Password-protected programs in vista does anybody know of a windows configuration (or an external tool/wrapper) to protect certain programs with a password ?
My pc is always running logged in with an administrator-level account but I'd like certain programs to be run only if a password is entered.

A: There are multiple "share-ware" applications out there that do this. A quick Google search will list many. I won't list them as I haven't used them and won't/can't personally recommend one.
What I will recommend is utilizing the Administrative account as it was intended. You should be running in the "least level of privilege" account possible and modify your application permissions to only allow admin to run it. Then use "Run as Administrator" to run what you want to use.
The fact that you are in an Admin account will subvert the purpose of folder locking as it will be easy to get around...


text:
Q: Redmi 6 - can't hang up phone I want to implement the function of hanging up the phone.
But in Redmi 6 (Android 8.1), it has not been possible.
I used the following two methods:
1.
TelecomManager telecomManager = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
if (telecomManager != null) {
     telecomManager.endCall();
}

Get the following error:
java.lang.SecurityException: Neither user 10179 nor current process has android.permission.MODIFY_PHONE_STATE

2.
TelephonyManager mTelMgr = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
Class<TelephonyManager> c = TelephonyManager.class;
try {
    Method getITelephonyMethod = c.getDeclaredMethod("getITelephony", (Class[]) null);
    getITelephonyMethod.setAccessible(true);
    ITelephony iTelephony;
    iTelephony = (ITelephony) getITelephonyMethod.invoke(mTelMgr, (Object[]) null);
    iTelephony.endCall();
} catch (Exception e) {
    e.printStackTrace();
}

Get the following error:
java.lang.SecurityException: MODIFY_PHONE_STATE permission required.

But in other mobile phone tests, it can be executed.
I don't know where the problem is.

A: From Documentation
MODIFY_PHONE_STATE
added in API level 1
public static final String MODIFY_PHONE_STATE
Allows modification of the telephony state - power on, mmi, etc. Does not include placing calls.

Not for use by third-party applications.

so your app cannot use this permission unless its system app or your device is rooted


text:
Q: Delete example folder in tomcat 8 I'm using a tomcat server in production stage project and it's handling high traffic.Now i need to remove example folder under webapp folder.Is it ok? are there any issue, if i remove that folder. I know example folder has no usefullness for the project.

A: I tested this in my test servers and It was safely deployed. And i tested this while sending high traffic. But there were no issue.


text:
Q: Excel: How to open the Data Entry form from VBA? There is a built-in data entry form in Excel. I have added a shortcut to this and its quite good. It has a few little issues (i.e. it depends what cell you have selected as to what data it fills in the form).
So I want to wrap it up into a macro and add my own button. My little macro will select the appropriate cell. So the question is, using VBA, how do you call the build-in Data Entry form?
-EDIT-
Seems my question is not clear... so here is some more:
There is a built-in data entry form that you can use, see here: Built-in Data Entry Form
I want to open this form using excel VBA, like this:
Sub OpenTheBuiltinDataEntryForm()
    ' Add code here to open the built-in data entry form...
End Sub

A: The line you are looking for is:
Activesheet.ShowDataForm

but note that your data table must begin within A1:B2 or be named Database or you will get an error.


text:
Q: Sed: save errors in a file I am writing script, I need to use sed for changing somefiles, I want to know if the operation failed by an error such as "No Such File" could I save the error in a text file or in a variable? and how?

A: sed -e 's/Some Text/Something else/' $file > output 2>errors

This redirects the errors (from stderr, file descriptor 2) to the file errors.

A: You can redirect the stderr by:
$yourcommand 2> log

*

*0 means stdin

*1 means stdout

*2 means stderr


text:
Q: Why does adb shell pm list permissions -g list more permissions than adb shell pm list permissions? As the title implies,
adb shell pm list permissions -g

returns more permissions than
adb shell pm list permissions

Does anybody know why this is the case?

A: It looks like pm list permissions without -g prints only ungrouped permissions. Here are the results from one of my phones:
Number of permissions printed out bypm list permissions:
$ pm list permissions | grep 'permission:' | wc -l
476

matches number of permissions in the ungrouped section of pm list permissions -g:
$ pm list permissions -g | sed -n '/ungrouped:/,$ p' | grep 'permission:' | wc -l
476

And when combined with the number permissions which belong to some group:
$ pm list permissions -g | sed -n '1,/ungrouped:/p' | grep 'permission:' | wc -l
33

It adds to the total number of permissions printed out by pm list permissions -g:
$ pm list permissions -g | grep 'permission:' | wc -l
509


text:
Q: How to rollup multiple directories separately with one output So, I have a directory:
mods/
-core/
--index.js
--scripts/
---lots of stuff imported by core/index

This works with typical rollup fashion if you want to rollup to for example mods/core/index.min.js
But I have many of these mods/**/ directories and I want to take advantage of the fact that they are rollup'd into iifes. Each mods/**/index.js will, rather than export, assign to a global variable that we presume is provided:
mods/core/index.js
import ui from './scripts/ui/'
global.ui = ui

mods/someMod/scripts/moddedClass.js
export default class moddedClass extends global.ui.something { /* some functionality extension */}

mods/someMod/index.js
import moddedClass from './scripts/moddedClass'
global.ui.something = moddedClass

So hopefully you can see how each mod directory can be rollup'd in typical fashion but, I need to then put the actual iifes inside another one so that:
mods/compiled.js
(function compiled() {
  const global = {};

  (function core() {
    //typical rollup iife
  })();

  (function someMod() {
    //typical rollup iife
  })();

  //a footer like return global or global.init()
})();

Any help towards this end would be greatly appreciated. The simplest possible answer, I think, is how I can simply get a string value for each mod's iife instead of rollup writing it to a file.
At that point I could just iterate the /mods/ directory, in an order specified by some modlist.json or something, and call rollup on each /mod/index.js, then build the outer iife myself from strings.
However, I suppose this would not be a full solution for sourcemapping? Or can multiple inline sourcemaps be included? With source mapping in mind, I wonder if another build step might be necessary, where each mod is transpiled before this system even gets to it.

A: Use rollup's bundle.generate api to generate multiple iifes and write them into one file using fs.appendFile.
For the sourcemaps you can use this module(it's from the same author of rollup) https://github.com/rich-harris/sorcery

A: Okay so the way I ended up solving this was using source-map-concat
It basically does what I described, right out of the box. The only thing I had to do was to asynchronously iterate the mod directory and rollup each mod, before passing the results to source-map-concat, since rollup.rollup returns a Promise.
I also ended up wanting in-line sourcemaps so that the code can be directly injected rather than written to a file, so I used convert-source-map for that.
The only issue left to solve is sub-source mapping. Sorcery would work great for that, if I was generating files, but I would like to keep it as string sources. For now it will at least show me what mod an error came from, but not the sub-file it came from. If anyone has info on how to do a sorcery-style operation on strings let me know.
Here's the relevant final code from my file:
const rollup  = require("rollup")
const concat  = require("source-map-concat")
const convert = require("convert-source-map")

const fs   = require("fs")
const path = require("path")

const modsPath = path.join(__dirname, "mods")

const getNames = _ => JSON.parse(fs.readFileSync(path.join(modsPath, "loadList.json"), "utf8"))

const wrap = (node, mod) => {
  node.prepend("\n// File: " + mod.source + "\n")
}

const rolls = {}
const bundles = {}

const rollupMod = (modName, after) => {
  let dir = path.join(modsPath, modName),
      file = path.join(dir, "index.js")

  rollup.rollup({
    entry: file,
    external: "G",
    plugins: []
  }).then(bundle => {
    rolls[modName] = bundle.generate({
      format: "iife",
      moduleName: modName,
      exports: "none",
      useStrict: false,
      sourceMap: true
    })

    after()
  })
}

const rollupMods = after => {
  let names = getNames(), i = 0,
      rollNext = _ => rollupMod(names[i++], _ => i < names.length - 1? rollNext() : after())

  rollNext()
}

const bundleCode = after => {
  rollupMods(_ => {
    let mods = concat(getNames().map(modName => {
      let mod = rolls[modName]

      return {
        source: path.join(modsPath, modName),
        code: mod.code,
        map: mod.map
      }
    }), {
      delimiter: "\n",
      process: wrap
    })

    mods.prepend("(function(){\n")
    mods.add("\n})();")

    let result = mods.toStringWithSourceMap({
      file: path.basename('.')
    })

    bundles.code = result.code + "\n" + convert.fromObject(result.map).toComment()

    after(bundles.code)
  })
}

exports.bundleCode = bundleCode


text:
Q: How to extend class which is in another Directory? I have a class called SeleniumUtility and try to extend PortalController (just for test).

I tried it like this:
<?php
namespace App\Http\Utility;

require_once(__DIR__.'/../Controllers/PortalController.php');

class SeleniumUtility extends PortalController
{
...

However, I get FatalErrorException in SeleniumUtility.php line 14:
Class 'App\Http\Utility\PortalController' not found
So it still tries to search in Utilty folder.
How does it work?

A: If you have an autoloader, such as a PSR-4 autoloader, you can implement the use syntax.
<?php
namespace App\Http\Utility;

use App\Http\Controllers\PortalContoller as PortalController;

class SeleniumUtility extends PortalController
{

...

A: You need to use like this.
class SeleniumUtility extends \App\Http\Controllers\PortalController
{

}

or
use App\Http\Controllers\PortalController;
class SeleniumUtility extends PortalController
{

}

A: According to you are using namespace change your code as below:
namespace App\Http\Utility;

require_once(__DIR__.'/../Controllers/PortalController.php');
use App\Http\Controllers as Controllers;
class SeleniumUtility extends Controllers\PortalController
{


text:
Q: Dealing with currency in PHP - decimal places & number_format() I need to store numbers that represent currency amounts in 2dp to be output to the screen. The same number may be altered with mathematical functions after being formatted. I'm sure I remember having errors in the past as a result of the number formatted number being treated as a string, and the thousand separator being the cause of the problem, but the below script runs without errors.
Is PHP's loose data types saving the day here? Did something change in a relatively recent PHP version? If not, are there other circumstances where number_format() can still cause a mathematical function to fail because the number is a string?
echo round(1111123.2, 2); //included to demonstrate how it can't be used for this purpose
echo "
";
echo number_format(1111123.2, 2);
echo "
";
$num = number_format(1111123.2, 2);
echo number_format($num / 42, 2);

// output
1111123.2
1,111,123.20
0.02

A:
The same number may be altered with mathematical functions after being formatted

Never do this. It's bound to end in tears, for example when you format numbers with non-english decimal separators. Do the operations on the raw numeric value, then format immediately before outputting.

A: This is due to the auto type-casting done by PHP. As far as I understand this, PHP will be able to type-cast to numbers in most generic mathematical functions, though, still not explicitely sure on this.
The strings are converted to required variable types

A: Well... The best thing is to store and calculate with "real" numbers (float, double or int) and use number_format() only for representation.
But if you need to calculate with figures which have been returned from number_format(), think about writing a function like
function unNumber_Format($str) {
   $search  = array(',', '$', '€');
   $replace = array('', '', '');

   return (double) str_replace($search, $replace, $str);
}

and using it like
echo number_format(unNumber_Format($num) / 42, 2);

and you're just fine! ;-)

A: Better is to use number formatter class:
however it requires the intl extension enabled and php 5.3.0+.. (sudo apt-get install php5-intl)
$f = NumberFormatter::create("en-US",NumberFormatter::CURRENCY);
var_dump($f->format(1111123.2));
$f = NumberFormatter::create("en-US",NumberFormatter::CURRENCY);
$f->setSymbol(NumberFormatter::CURRENCY_SYMBOL,"€");
var_dump($f->format(1111123.2));
$f = NumberFormatter::create("de_DE",NumberFormatter::CURRENCY);
var_dump($f->formatCurrency(1111123.2,"EUR"));
$f = NumberFormatter::create("it_IT",NumberFormatter::CURRENCY);
var_dump($f->formatCurrency(1111123.2,"USD"));
$f = NumberFormatter::create("sk_SK",NumberFormatter::CURRENCY);
var_dump($f->formatCurrency(1111123.2,"USD"));

Returns:
string(13) "$1,111,123.20"
string(15) "€1,111,123.20"
string(17) "1.111.123,20 €"
string(17) "US$ 1.111.123,20"
string(19) "1 111 123,20 US$"

If your customers are from different countries, just store for them the locale, and they will get their predefined number.


text:
Q: How can i make a reusable labelFunction for Flex Datagrid? I have a label function like :
private function formatDate (item:Object, column:DataGridColumn):String
{
    var df:DateFormatter = new DateFormatter();
    df.formatString = "MM/DD/YY";

    if (column.dataField == "startDate") {
        return df.format(item.startDate);
    }

    return "ERR";
}

Which I use in a datacolumn by using labelFunction.
This works just fine if my data field is called 'startDate'. I want to make this function generic so I can use it everywhere.
How can I do this. i think i need to use some kind of 'reflection' - or perhaps another approach altogether?

A: You can make the function generic using the dataField attribute of the column as the key into your item.
private function formatDate (item:Object, column:DataGridColumn):String
{
    var df:DateFormatter = new DateFormatter();
    df.formatString = "MM/DD/YY";

    var value:object = item[column.dataField];

    return df.format(value);
}

-Ben

A: You can define another function, let's call it partial that binds some extra arguments to your function:
function partial( func : Function, ...boundArgs ) : Function {
  return function( ...dynamicArgs ) : * {
    return func.apply(null, boundArgs.concat(dynamicArgs))
  }
}

Then you change your function like this:
private function formatDate( dataField : String, item : Object, column : DataGridColumn ) : String {
  var df : DateFormatter = new DateFormatter();

  df.formatString = "MM/DD/YY";

  if ( column.dataField == dataField ) {
    return df.format(item[dataField]);
  }

  return "ERR";
}

Notice that I have added a new argument called dataField first in the argument list, and replaced all references to "startDate" with that argument.
And use it like this:
var startDateLabelFunction : Function = partial(formatDate, "startDate");
var endDateLabelFunction   : Function = partial(formatDate, "endDate");

The partial function returns a new function that calls the original function with the parameters from the call to partial concatenated with the parameters to the new function... you with me? Another way of putting it is that it can return a new function where N of the arguments are pre-bound to specific values.
Let's go through it step by step:
partial(formatDate, "startDate") returns a function that looks like this:
function( ...dynamicArgs ) : * {
  return func.apply(null, boundArgs.concat(dynamicArgs));
}

but the func and boundArgs are what you passed as arguments to partial, so you could say that it looks like this:
function( ...dynamicArgs ) : * {
  return formatDate.apply(null, ["startDate"].concat(dynamicArgs));
}

which, when it is called, will be more or less the same as this
function( item : Object, column : DataGridColumn ) : * {
  return formatDate("startDate", item, column);
}

Tada!

A: here is more generic way:
public static function getDateLabelFunction(dateFormatString:String=null, mxFunction:Boolean = false) : Function {
        var retf:Function;

        // defaults
        if(dateFormatString == null) dateFormatString = "MM/DD/YY";
        if(mxFunction) {
            retf = function  (item:Object, column:DataGridColumn):String
            {
                var df:DateFormatter = new DateFormatter();
                df.formatString = dateFormatString;

                var value:Object = item[column.dataField];

                return df.format(value);
            }
        }else {
            retf = function  (item:Object, column:GridColumn):String
            {
                var df:DateFormatter = new DateFormatter();
                df.formatString = dateFormatString;

                var value:Object = item[column.dataField];

                return df.format(new Date(value));
            }
        }

        return retf;

    }

Usage (Spark DataGrid)
var labelFunction = getDateLabelFunction();

or for MX Datagrid
var labelFunction = getDateLabelFunction(null,true);

to pass custom Date Format String:
var labelFunction = getDateLabelFunction("DD/MM/YYYY",true);

Default is a "MM/DD/YYYY";


text:
Q: Syntax/pre-compilation issue with graphql and express Hi I am following this video to make a booking system enter link description here
And my code is identical to the creator but it isn't running (error message shown below)
    [nodemon] restarting due to changes...
[nodemon] starting `node app.js`
C:\Users\Abdulrahman\Desktop\bookings1\app.js:12
    graphqlHttp({
    ^

TypeError: graphqlHttp is not a function
    at Object.<anonymous> (C:\Users\Abdulrahman\Desktop\bookings1\app.js:12:5)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47
[nodemon] app crashed - waiting for file changes before starting...

And code in the app.js file is
const express = require('express');
const bodyParser = require('body-parser');
const graphqlHttp = require('express-graphql');
const { buildSchema } = require('graphql');

const app = express();

app.use(bodyParser.json());

app.use(
    '/graphql',
    graphqlHttp({
        schema: buildSchema(`
        type RootQuery {
            events: [String!]!
        }
        type RootMutation {
            createEvent(name: String): String
        }
        schema {
            query: RootQuery
            mutation: RootMutation
        }
    `),
        rootValue: {
            events: () => {
                return ['Romantic Cooking', 'Sailing', 'All-Night Coding'];
            },
            createEvent: (args) => {
                const eventName = args.name;
                return eventName;
            }
        },
        graphiql: true
    })
);

app.listen(3000);

Any ideas how to fix this error? To get to this debugger? Thanks alot as I've been stuck on this for a while!

A: To fix the error TypeError: graphqlHttp is not a function, replace
const graphqlHttp = require('express-graphql');

with
const { graphqlHTTP } = require('express-graphql');

(Notice the different case for HTTP, versus Http)
Of course, in the other lines, graphqlHttp must be replaced by graphqlHTTP.
https://graphql.org/graphql-js/express-graphql/


text:
Q: How to move onto the next iteration of a loop within a loop in python? Take for example the code below with 2 for loops.
for xy in set:
        for name in dict:
            if xy == name:
               print("Yay")

What I'm wondering is, if after the if statement is found to be true, will it keep iterating through 'dict' or will it go back upto the first for loop and move onto the next iteration? I can't believe how long I've been using python and I don't know the answer to such a simple question.
Thanks!

A: It will continue to iterate in dict. If you want to jump out of the inner loop, use break.
You can also try.
if any(name in dict for name in set):
    print('Yay')

A: It keep iterate through dict.
If you want the loop  go back upto first for loop, use break statement:
for xy in set:
    for name in dict:
        if xy == name:
           print("Yay")
           break

As Jacob Krall commented, You don't need to iterate the dictionary object to check whether key(name) exist. Use in operator:
>>> d = {'sam': 'Samuel', 'bob': 'Robert'}
>>> 'bob' in d
True
>>> 'tom' in d
False

for xy in set:
    if name in dict:
        print("Yay")

If you want print Yay only once, use set.isdisjoint:
if not set.isdisjoint(dict):
    print("Yay")

BTW, do not use set or dict as variable name. It shadows builtin function set, dict.

A: It will continue to iterate over dict. If you do not want this behavior try this:
for xy in set:
    for name in dict:
        if xy == name:
           print("Yay")
           break


text:
Q: Create Spaces in a query in order to export csv file
Possible Duplicate:
PHP code to convert a MySQL query to CSV

i'm trying to export a csv file and i'd need to create space between the fields of the database printed because everything comes as a simple row.
What i need to do is also print in the header the name of the field.. here is the code i have. First i need to export fields in a csv tab or just space between fields...
if ( !$result1 ) { echo mysql_error(); }
while ($row = mysql_fetch_array($result1)) {
    $last = end($row);
    foreach ($row as $item) {
        fwrite($fh, $item);
        if ($item != $last)
            fwrite($fh, "\t");
    }
    fwrite($fh, "\n");
}
fclose($fh);

A: You might consider using fputcsv instead of this hassle with fwrite. The syntax is like this:
int fputcsv ( resource $handle , array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]] )

For your code it would look like:
$fh = fopen('file.csv', 'w');
if ( !$result1 ) { echo mysql_error(); }
while ($row = mysql_fetch_array($result1)) {
    fputcsv($fh, $result1, ',');
}
fclose($fh);

The optional $enclosure parameter can be used if you need to use other quotes for the string values (double quotes is standard).

A: Try this in foreach
fwrite($fh, $item.',');
Have a look at
http://net.tutsplus.com/tutorials/php/how-to-generate-a-complete-excel-spreadsheet-from-mysql/


text:
Q: php turn words to full-width Is there any method to change words to full-width like:
123 ->123
Because I have to turn Japanese words to full-width, I cannot use some way like enumeration.
( like: str_replace('1','1',$string); str_replace('2','2',$string); ... and so on.)
How do I solve the problem?
And, is it possible to force user typing full-width words?
My web is written in PHP, and I know how to combine with javascript.
The typing I already clarify is like:
onKeyUp="value=value.replace(/[\x00-\xff]/g,'')"

(The upper regular expression is enable user typing Japanese like 'カメラ', Chinese like '你好', and full-width words, that is what I want.)
But I don't know how to force the user typing full-width words; like  can force user input English or numeric words.( Or it is impossible to do it)
Any replying appreciate!

A: There are several options to achieve this but I think the easiest is to use the kbd HTML tag:
<kbd>Some text in here</kbd>
You can also try an experimental CSS solution:
p {
  text-transform: full-width
}

Finally, try CSS letter-spacing to achieve a similar effect with the right font.