text:
Q: PowerShell script generates lots of warnings in Windows Event Log I have a - rather complex - PowerShell script running on a Windows Server 2008 R2. When executing the script in the ISE or also in the console, everything runs fine. No errors or anything else that would stand out.
However, in the Windows Event viewer lots of Warnings are being generated without any specific reason that I can see.
Log Name: Microsoft-Windows-PowerShell/Operational

Source: PowerShell (Microsoft-Windows-PowerShell)

Event ID: 4100

Task Category: Executing Pipeline

    Error Message = System error.
    Context:
    Severity = Warning
    Host Name = Windows PowerShell ISE Host
    Host Version = 4.0
    Host ID = cec010f3-ea0f-44b0-8d2e-449a6c1eb3e6
    Engine Version = 4.0
    Runspace ID = b2e8d39c-4fa1-4a3f-b33e-b42f8b552c3d
    Pipeline ID = 17
    Command Name =
    Command Type =
    Script Name =
    Command Path =
    Sequence Number = 92
    User = [the executing user]
    Shell ID = Microsoft.PowerShell

    User Data:

Google did not reveal anything. Does anyone have an idea what this could mean? As I said, there are hundrets of those entries. Let me know if I should post anything more.
Thanks a lot!
edit: As requested the entire event XML
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Microsoft-Windows-PowerShell" Guid="{A0C1853B-5C40-4B15-8766-3CF1C58F985A}" />
<EventID>4100</EventID>
<Version>1</Version>
<Level>3</Level>
<Task>106</Task>
<Opcode>19</Opcode>
<Keywords>0x0</Keywords>
<TimeCreated SystemTime="2015-03-16T14:06:07.066866300Z" />
<EventRecordID>1994921</EventRecordID>
<Correlation ActivityID="{01EC0C48-F800-0001-6B28-234CAE5DD001}" />
<Execution ProcessID="6528" ThreadID="5376" />
<Channel>Microsoft-Windows-PowerShell/Operational</Channel>
<Computer>[host]</Computer>
<Security UserID="S-1-5-21-1482476501-1450960922-725345543-2410959" />
</System>
<EventData>
  <Data Name="ContextInfo">Severity = Warning Host Name = Windows PowerShell ISE Host Host Version = 4.0 Host ID = cec010f3-ea0f-44b0-8d2e-449a6c1eb3e6 Engine Version = 4.0 Runspace ID = b2e8d39c-4fa1-4a3f-b33e-b42f8b552c3d Pipeline ID = 36 Command Name = Command Type = Script Name = Command Path = Sequence Number = 7665 User = [user name] Shell ID = Microsoft.PowerShell</Data>
  <Data Name="UserData" />
  <Data Name="Payload">Error Message = System error.</Data>
</EventData>
</Event>

Added PS D:\Autonomy\cd_provisioning_client> ($PsVersionTable)
Name                           Value
----                           -----
PSVersion                      4.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34209
BuildVersion                   6.3.9600.16406
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.2

powershell_ise.exe.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" />
</startup>
</configuration>

A:
When executing the script in the ISE or also in the console,
  everything runs fine. No errors or anything else that would stand out.

Runs fine doesn't means there is no errors encountered. Your script probably just ignores them, using -ErrorAction SilentlyContinue parameter with cmdlets. Example:
Get-ChildItem -LiteralPath ZZZ:\

This will generate so called terminating error and will stop the current pipeline, but because the ErrorActionPreference variable is by default set to Continue, the script itself will continue execution. And, as you can see, PowerShell host will log this error to the Event Log.
If you'd like to debug your script and find what error causes this log record, set $ErrorActionPreference to Stop at the beginning of your script and run it. The first encountered error will stop the script execution and then you can view the error details like this $Error[0].
UPDATE: I'm at loss, since everything we've tried didn't led to substantial result:

*

*$Error variable is empty

*Set-StrictMode -Version Latest didn't catch anything

*$PsVersionTable and powershell_ise.config are looking fine to me

It's definitely something strange going on here and I don't believe that those empty fields are normal:
Command Name =
Command Type =
Script Name =
Command Path =

While I still have some ideas to try, they require more thorough research:

*

*Check your script for any non-PowerShell objects\method (third-party assemblies, COM-Objects, etc...) and try to comment them out.

*Try monitoring PowerShell process with Process Monitor
Good luck!


text:
Q: System.Windows.Forms.Application.Restart(); does load the application straight away? I have a logic in the MainWindow() as the following. What happens is that after I upload the license file and the DXWindow is closed I call this
System.Windows.Forms.Application.Restart();
                        Application.Current.Shutdown(); and I notice it straight away start my application it does not check the logic in the MainWindow() anymore. How to force it to get back into the MainWindow() when I run the restart ?
public MainWindow()
        {
           bool licStatu = IsValidLicenseAvailable();

            if (licStatu == false)
            {
                if (licStatu == false)
                {

                    DXWindow1 l1 = new DXWindow1();
                    l1.ShowDialog();
                    if (l1.DialogResult.HasValue && !l1.DialogResult.Value)
                        Application.Current.Shutdown();
                    else {
                        System.Windows.Forms.Application.Restart();
                        Application.Current.Shutdown();
                    }
                }
            }
            else
            {

                if (IsValidLicenseAvailable() == false)
                {

                    DXWindow1 l1 = new DXWindow1();
                    l1.ShowDialog();
                    if (l1.DialogResult.HasValue && !l1.DialogResult.Value)
                        Application.Current.Shutdown();

                }
                else {

                    if (crossDay == 0 )
                    {
                        // MessageBox.Show("al okCross day :" + crossDay);
                        InitializeComponent();
                     }
              }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to run a long .sql file through Codeigniter? I want to run a .sql file from my server in Codeigniter 3.1.0. I have tried following
//code to create a DB & this is successful then following ocde
$query = file_get_contents('./test.sql');
$this->db->query($query);

Here is my test.sql file. https://gist.github.com/rejoan/97dfae1b08116e386b3e6fda97eeb4f7
Now when I run this it shows error always

A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'CREATE TABLE user ( id int(11) NOT NULL, test_id int(11)
  NOT NULL, `' at line 10

CREATE TABLE `test`
( `id` int(11) NOT NULL,
`name` varchar(250) NOT NULL,
`description` text NOT NULL,
`added` date NOT NULL,
`outdate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `user`
( `id` int(11) NOT NULL,
`test_id` int(11) NOT NULL,
`name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `test` ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `name` (`name`);

ALTER TABLE `user` ADD PRIMARY KEY (`id`),
ADD KEY `test_id` (`test_id`);

ALTER TABLE `test` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37;

ALTER TABLE `user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

ALTER TABLE `user`
ADD CONSTRAINT `FK_user_test` FOREIGN KEY (`test_id`)
REFERENCES `test` (`id`) ON UPDATE NO ACTION;

Filename: C:/xampp/htdocs/spider_clients/system/database/DB_driver.php
Line Number: 691

So how can I resolve this by issue? I have a idea to do this by PHP raw code but Firstly I want to solve by CI. Any Idea?
** Even I have tried by replacing all backtick by single quote still not works

A: You can't run any SQL file through the API. Not even if you split up the file and run one query per API call.
There are some commands that can appear in SQL files, but they're actually mysql client builtin commands. These commands are not recognized by the SQL parser in the server.
It's tricky to split up the SQL file. There are SQL statements that contain literal semicolons, like CREATE TRIGGER. So you need more complex logic to split up the file, it's not as simple as preg_split('/;/', $query)
Another gotcha: you'll find that submitting a "query" that consists of nothing but an SQL comment causes an error.
Also, if your SQL file is too large, you'll blow out PHP's max memory if you use file_get_contents().
The bottom line is that you'll waste a lot of your time developing this code and trying to make it work. You're better off leveraging the tool that is already designed to run SQL scripts:
shell_exec("mysql databasename < ./test.sql");

See also:

*

*Running MySQL *.sql files in PHP


text:
Q: NHibernate 3.1.0.4000 QueryOver SQL Optimisation I have Entity 'Content'. Each Content has a 'Placement' property. Placement has a many-to-many relationship width 'AdType' entity (Placement has IList<\AdType> property mapped).
I need to load all Placements that are used at least in one Content and associated width specified AdType.
My DAL function looks like this:
    public IList<Placement> Load(AdType adType)
    {
        return NHibernateSession.QueryOver<Content>()
            .JoinQueryOver(content => content.Placement)
            .JoinQueryOver<AdType>(placement => placement.AdTypes)
            .Where(_adType => _adType.Id == adType.Id)
            .Select(x => x.Placement).List<Placement>();
    }

This works fine but when I look to the SQL log i see:
SELECT this_.PlacementId as y0_ FROM AdManager.dbo.[Content] this_ inner join AdManager.dbo.[Placement] placement1_ on this_.PlacementId=placement1_.PlacementId inner join AdManager.dbo.AdTypeToPlacement adtypes5_ on placement1_.PlacementId=adtypes5_.PlacementId inner join AdManager.dbo.[AdType] adtype2_ on adtypes5_.AdTypeId=adtype2_.AdTypeId WHERE adtype2_.AdTypeId = @p0

SELECT placement0_.PlacementId as Placemen1_26_0_, placement0_.Name as Name26_0_ FROM AdManager.dbo.[Placement] placement0_ WHERE placement0_.PlacementId=@p0

SELECT placement0_.PlacementId as Placemen1_26_0_, placement0_.Name as Name26_0_ FROM AdManager.dbo.[Placement] placement0_ WHERE placement0_.PlacementId=@p0

This means that NHibernate takes all placements Id in first query and then queries all fields from Placement table by Id.
My question is: Does enyone know how to modify QueryOver method to force NHibernate load data in one query?

A: it seems NHibernate does think there might be something in the where which maybe filters out data which is needed tro initialize the placement. You can go with a subquery:
public IList<Placement> Load(AdType adType)
{
    var subquery = QueryOver.For<Content>()
        .JoinQueryOver(content => content.Placement)
        .JoinQueryOver<AdType>(placement => placement.AdTypes)
        .Where(_adType => _adType.Id == adType.Id)
        .Select(x => x.Id);

    return NHibernateSession.QueryOver<Content>()
        .WithSubquery.Where(content => content.Id).IsIn(subquery))
        //.Fetch(x => x.Placement).Eager   try with and without
        .Select(x => x.Placement).List<Placement>();
}

or SQL (has the disadvantage that it just fills the new Placement but doest track it)
public IList<Placement> Load(AdType adType)
{
    return NHibernateSession.CreateSQLQuery("SELECT p.Name as Name, ... FROM content c join placement p...")
        .SetResultTransformer(Transformers.AliastoBean<Placement>())
        .List<Placement>();
}


text:
Q: Where should I `initdb` on a first postgres install? Setting up a development environment on a new machine, brew installed postgres. Now I need to initdb for the first time, which directory should i specify for this command?

A: Assuming you're on OS X, given "brew", then:

*

*If you intend to run the postgres server under your own user account, put it somewhere like /Users/MyUserName/Library/postgres_data.

*If you intend to run it from launchd as a system service, as a dedicated postgres user, put it somewhere in /Library/.
However, Homebrew takes this out of your hands a bit with brew services:
brew tap homebrew/services

which I recommend using. I don't have a Mac and the docs appear to be nonexistent for this, but it looks like it's as simple as:
brew services start postgres

If not, the interactive help will probably tell you what you need to do.

A: It seems brew failed to create a database when installing postgres, the solution for me, as found here, was to run createdb then all was fine.


text:
Q: ( was unexpected at this time - batch script I'm using the batch script below and get an error

( was unexpected at this time.

I know that the problem is in the first line but I don't understand what is wrong.
Any ideas ?
script:
IF [%1]==[] (
    :LOOP1
    SET /P isDefault=Value Missing, do you want to use default values [1,1,10,Local      Area Connection 2]?[y/n]
    IF %isDefault%==y (
        SET from=1
        SET step=1
        SET to=10
        SET lan="Local Area Connection 2"
        GOTO :USERLOOP
    )
    IF %isDefault%==n GOTO :END
    GOTO :LOOP1
)

A: As jamesdlin said, it's a problem with empty variables and also with delayedExpansion.
Then the solution is simple by replacing %isDefault% with !isDefault!, this works even if isDefault is empty.
setlocal EnableDelayedExpansion
IF [%1]==[] (
    :LOOP1
    SET /P isDefault=Value Missing, do you want to use default values [1,1,10,Local      Area Connection 2]?[y/n]
    IF !isDefault!==y (
        SET from=1
        SET step=1
        SET to=10
        SET lan="Local Area Connection 2"
        GOTO :USERLOOP
    )
    IF !isDefault!==n GOTO :END
    GOTO :LOOP1
)

A: I had a very similar problem and code construct that was causing me a lot of pain to resolve. My error message was ". was unexpected at this time"...
It took me a couple long days to figure out another similar consideration due to this problem... Please take a look a the following problem and subsequent solution here: ". was unexpected at this time" generated from batch script line 'if exist [file] (...
The solution was simply the treatment of '(' and ')' on ECHO lines inside an IF statement block.
The point is, do consider treatment of special characters as a possible source of a problem when troubleshooting IF (and possibly FOR) statements.
HTH someone...

A: Actually, the problem is not on the first line.
The problem is that cmd does variable substitution immediately when it parses the IF statement, including its body.  Therefore the line:
IF %isDefault%==y (

is problematic because isDefault isn't set when the outer IF statement is parsed, so it becomes:
IF ==y (

and hence you get the error about ( being unexpected.  You can get around this by enabling the command extension (SETLOCAL ENABLEDELAYEDEXPANSION) for delayed environment variable expansion (see set /? for details).  You also can rewrite your script:
@ECHO OFF
IF NOT "%1"=="" GOTO :EOF

:LOOP1
SET /P isDefault=Value Missing, do you want to use default values [1,1,10,Local Area Connection 2]?[y/n]
IF "%isDefault%"=="y" (
    SET from=1
    SET step=1
    SET to=10
    SET lan="Local Area Connection 2"
    GOTO :USERLOOP
)
IF "%isDefault%"=="n" GOTO :EOF
GOTO :LOOP1

(I made some other changes, such as using the built-in :EOF label instead of :END.)


text:
Q: Why validating/invalidating the area is used? When a part of the window needs to be repainted, the area is marked as invalid, and when I repaint the area (in the WM_PAINT event handler), I should mark the area as valid.
But I don't understand what is the need for marking the area as invalid and then validating it later, I mean why not just do the following: when an area needs to be repainted, just send a WM_PAINT message (without marking the area as invalid) and then just repaint the area (without marking it as valid).

A: Marking an area as INVALID lets windows know that it is in need of updating. This is to allow partial paints of the screen instead of just completely updating the draw area every pass.
It's a good idea to only invalidate areas of change in mostly static programs to reduce draw overhead.
Validating them after the draw has completed lets windows know that the area has been refreshed and does not need to be redrawn again.
An example of where this would be useful is when you have the following type of window:

When scrolling through the list boxes or ticking the check boxes it is better to only invalidate that area of the window for redraw rather than redrawing the whole window every time the list box or check box needs to be updated to show the new scroll position or check mark.

A: Imagine someone's throwing balls at a fence. Do you repaint the fence as many times as balls hit it? No, you repaint the fence if, and only if, a ball hit it since the last time you repainted.
You're suggesting that any time an area would be marked invalid, instead a WM_PAINT message should be sent to the application. The big problem with this is that if the same area got invalidated many times, that would result in many WM_PAINT messages being sent and no way to know that many of them have already been handled. So at the time when you most need high performance (because you're falling behind on drawing) you'd have to repeat the same drawing operations over and over. That doesn't make sense.


text:
Q: Bluemix Create App Error Getting the below error while creating app on Bluemix dashboard, irrespective of using unique App names

BXNUI0005E: The 'MyFirstMobileAppTest' application could not be added.
  See the Troubleshooting topics in the IBM Bluemix Documentation to
  check service status, review troubleshooting information, or for
  information about getting help.

A: I have been able to create a mobile application without any problems. This issue was most likely due a temporary outage.
If you experience this again, be sure check the Bluemix status page for any known issues and/or try again in a few minutes.


text:
Q: Why do C++ STL container begin and end functions return iterators by value rather than by constant reference? As I look at the standard for different STL objects and functions, one thing that doesn't make sense to me is why would the begin() and end() functions for container objects return an iterator by value rather than by constant reference? It seems to me that iterators could be held by the container object internally and adjusted whenever the container is mutated. This would mitigate the cost of creating unnecessary temporaries in for loops like this:
for (std::vector<int>::iterator it=my_vec.begin(); it!=my_vec.end(); ++it){
    //do things
}

Is this a valid concern? Is there something about using references to iterators that makes this a bad idea? Do most compiler implementations optimize this concern away anyway?

A: Iterators are designed to be light-weight and copyable (and assignable). For example, for a vector an iterator might literally just be a pointer. Moreover, the whole point of iterators is to decouple algorithms from containers, and so the container shouldn't have to care at all what kind of iterators anyone else is currently holding

A: If the begin and end methods returned a reference, the container would be forced to have each of those iterators as members. The standards people try to leave as much flexibility to an implementation as possible.
For example you can create a simple wrapper for an array that behaves as a standard container and doesn't consume any extra memory. If this wrapper were required to contain the iterators it wouldn't be so simple or small anymore.

A: Well, if you choose right iterator, STL would :-)
for (
    std::vector<int>::const_iterator it=my_vec.begin(),
    end=my_vec.end();
    it!=end;
    ++it)
{
    //do things
}

Iterator in STL has pointer-semantic. Const iterator has const pointer semantic.


text:
Q: TsLint: function invocation disallowed I have some TypeScript code like this in my Visual Studio project
if (_.isNull(user)) {
  //Do stuff
}

And on save, TSLint gives me
Message TsLint: function invocation disallowed: _.isNull    BaseCtrl.ts    127

I do have the TypeScript definitions for Underscore.js in my project.
What does this message mean & how do I either fix my code to make TSLint happy or turn off this message in my tslint.json project settings?

A: I believe this is an issue with using isNull which appears to be on the function ban list.
https://github.com/palantir/tslint/blob/master/src/rules/banRule.ts
The default ban list that comes with Web Essentials includes three ban rules:
"ban": [true,
       ["_", "extend"],
       ["_", "isNull"],
       ["_", "isDefined"]
 ],


text:
Q: Segmentation Fault while trying to fill a list I'm trying to implement a memoryboard for the sensehat on a raspberry
I got a struct that gives x and y coordinates while trying to fill them with random int i get segmentation faults.
  struct point_list *next;
  int x;
  int y;
};

struct segment_points{
  struct point_list *head;
};

struct segment_points points = {
    NULL,
};

void addNewPoint(){

    struct point_list *point_i = points.head;
    struct point_list *new_tail;
    struct point_list new_tail1;
    new_tail = &new_tail1;

    while(point_i != NULL && point_i->next != NULL){
        point_i = point_i->next;

    }

    new_tail->x = rand() % 8;

    new_tail->y = rand() % 8;

    new_tail->next = NULL;
    if(point_i != NULL){
        point_i->next = new_tail;
    }else{
        points.head = new_tail;
    }

    /*for(point_i = points.head; point_i->next; point_i->next != NULL){

            render(point_i->x,point_i->y);
    }*/

}
// for loop in main for testcase
for(int i=0; i <= 5; i++){
        printf("test\n");
        addNewPoint();
    }

i tried some printf to find out when the segmentation fault kicks in and its after the second time he goes into the whileloop


text:
Q: How to build and maintain a library for multiple languages? I need to implement a library which will be called from multiple languages - Java, Python, Perl and possibly more in the future. I'd hate to implement (and maintain) the same thing again and again in multiple languages.
One option I can think of is to write the core functionality in C/C++ and use SWIG to generate bindings for target languages; or maybe write the bindings myself.
Thre are some reasons why it can't be an independent service.
Are there any other mature alternatives? I am looking for options to compare before I settle for one.
Ideally, I'd like to do it using a source to source compiler or a source code generator. But I can't find one that supports all of the above languages - with potential for future additions.
I may consider any alternative binding generators if they provide any advantages over SWIG.
Thanks in advance for any pointers!

A: The simplest way is to write the library in C with a simple API.  Every non-obscure language has some way to interface with C code.
Depending on the style of the API, SWIG can save some time in generating the bindings; but unless it's very big and regular, you might find it easier to write the bindings by hand.
Some Languages (at least Python in your question) have an FFI mechanism, that lets you write the whole binding in the target language, making it much easier to deploy and maintain.  Note that most of those are focused on C APIs, not C++.

A: Depends on how you plan on access the library, is it possible to expose the public API via Web Services?
This way you can write the shared module in any language and access it via a common protocol such as a RESTfull web service.
Look at Microservices architecture.


text:
Q: Need to search record with missing one value in column out of multiple record for the same date in MYSQL I have below sample data in mysql db
SC_ID   PAY_TY  PAY_SB_TY FY      PAY_DT       AMOUNT
S01     CASH              2014    12302014     142
S01     CREDIT  AE        2014    12302014     150
S01     CREDIT  Debit     2014    12302014     11
S01     Debit   DEBIT     2014    12302014     10
S01     CREDIT  visa      2014    12302014     23
S01     CREDIT  visa New  2014    12302014     12.5

these are record for one date 30 dec 2014, I need to find the date where there is no record for 'visa'
i.e. all rows are present but PAY_SB_TY='visa' is not present.
Please suggest how to do

A: Use a where not exists clause.
SELECT *
FROM tbl t
WHERE NOT EXISTS
  (SELECT 1 FROM tbl
   WHERE Pay_SB_Ty='Visa'
   AND Pay_Dt = t.Pay_Dt)


text:
Q: 'cross-env' is not recognized as an internal or external command, Guys can you please help me on this I have trouble run npm run dev for my Laravel Mix. I followed links below but still error exist. Do i have a problem on my OS? I tried to remove node_modules, run npm install --global cross-env. and run NPM install again.

https://github.com/JeffreyWay/laravel-mix/issues/478
Laravel 5.4 'cross-env' is not recognized as an internal or external command
Here are my versions:

*

*Laravel mix version: ^2.0

*Node Version (node -v): 8.9.0

*NPM Version (npm -v): 5.6.0

*OS: Windows7

*XAMPP

> @ development C:\xampp\htdocs\codetinerant
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

'cross-env' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Garciano\AppData\Roaming\npm-cache\_logs\2018-02-17T10_08_34_901Z-debug.log

A: First, run:
rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force

Then run the command
npm install cross-env

npm install

and then you can also run
npm run dev

A: Try install cross-env globally.
run
sudo npm i -g cross-env

A: Did you try specifying the path to cross-env as suggested by dwoodward on the Github issue you linked. This goes in your package.json file:
"dev": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch-poll": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --watch-poll --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"hot": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"production": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"

This may have changed in more recent versions of Laravel but the gist is that you should change cross-env to node_modules/cross-env/dist/bin/cross-env.js.

A: Try Add the npm bin directory to your system path
e.g C:\Users\DELL\AppData\Local\Yarn\bin

A: I resolved it by uninstalling node and then running the following command.
npm install -d


text:
Q: Drupal Add Static link to a view I have a Drupal view that lists a node called publication. At the top of the page I'd like to have a link 'new publication' instead of having it in the navigation block.  Can somebody direct me on how to go about this?  There seems to be several ways but I'm having little luck.

A: You can also use the following module: https://www.drupal.org/project/views_linkarea.
As stated in its description,

"By making it a real link rather than just a blob of HTML in a header
  text area it gets all of the special handling and clean URL
  friendliness and base-path portability that any Drupal link gets."

A: Edit: Just realized that I probably misunderstood your question. You want a link on the top of every page, pointing to your view?

(Note: probably not what the OP wants, as it would put the link at the top of the view itself)
One of the easiest ways would be to put it in the 'header' section of the view (under 'basic settings' on your views configuration page). You can set a filter format for this, so make sure to use one that allows links.

A: I also struggled a bit in getting the exact meaning of your question.
I understand your question like this: "I have various pages of node listing generated by my view, I would like to have on top of each of these pages a link that allows me to create a new node of the type listed in the views. How do I do it?"
If I got your question right, a possible method is to insert the link in the template for your view. In fact the link to create a new node of that type will be a static URL of the type
http://example.com/node/add/mynodetype

so you can safely put in your template file something like:
<?php print(l('Create a new mynodetype article!', 'node/add/mynodetype')) ?>

This is substantially equivalent to what Henrik proposed (+1) by modifying the header of your view. What method you choose will probably depend on if you consider this link more of a core feature of your view or more of a theming element. If you add it to the view, you will have it in all your themes (=feature). If you put it in the template, you will only have it for the theme the template is used by (=theming element). Of course - even if it is a theme element - it makes more sense to include it to the view if you use a standard template file, so you will not have to crate an entire template file just for a link.
From your comment below it seems that you are not already using a template for your view, and therefore - unless you need it - you could go with Henrik's suggestion of adding the information in the header of the view. I however prepared screenshots to illustrate both methods:
Adding to the header:
You have to click on "header", then insert the code in the textfield and set the input filter to "PHP" (Otherwise your code will be escaped and displayed instead of being run).

Creating a template:
You have to click on "information: theme" and then you will have a list of possible template names. The one in bold is the one currently used. You then have then to copy the file with the bold name (from the views directory) to your theme directory, and rename it in one of the proposed ways. Then you can enter the file and edit it adding the PHP code you need.
As stated before: if you do not need a template for anything else, then creating a theme only for this is overshooting, IMO.


text:
Q: VTD-XML element fragment incorrect When parsing a XML document (in UTF-8) containing a special character like © using VTD-XML I now encounter an issue that the returned element fragment (getElementFragment) is not correct.
Example code:
VTDGen vg = new VTDGen();
String xmlDocument =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
        "<Root>\r\n" +
        "  <!-- © -->\r\n" +
        "  <SomeElement/>\r\n" +
        "</Root>";
// For some reason with US_ASCII it does work, although the file is UTF-8.
vg.setDoc(xmlDocument.getBytes(StandardCharsets.UTF_8));
// True or false doesn't matter here, some result.
vg.parse(false);
// Find the element and its fragment.
VTDNav nv = vg.getNav();
AutoPilot ap = new AutoPilot(nv);
ap.selectXPath("//SomeElement");
while ((ap.evalXPath()) != -1) {
    long elementOffset = nv.getElementFragment();
    int contentStartIndex = (int)elementOffset;
    int contentEndIndex = contentStartIndex + (int)(elementOffset>>32);
    System.out.println("Returned fragment: " + contentStartIndex + ":" + contentEndIndex + ":\n'" + xmlDocument.substring(contentStartIndex, contentEndIndex) + "'");
}

This returns:
Returned fragment: 65:79:
'SomeElement/>
'

While when changing the StandardCharsets.UTF_8 into StandardCharsets.US_ASCII it does work:
Returned fragment: 64:78:
'<SomeElement/>'

When the input file is a UTF-8 file, this leads to incorrect behaviour. Can this be a bug in VTD-XML, or am I doing something wrong here?

A: The "©" is a two-word unicode char which causes the starting/ending unicode offset to drift from the starting/ending byte offset by 1. This is not a bug... below is the fix
while ((ap.evalXPath()) != -1) {
            long elementOffset = nv.getElementFragment();
            int contentStartIndex = (int)elementOffset;
            int contentEndIndex = contentStartIndex + (int)(elementOffset>>32);
            System.out.println("Returned fragment: " + contentStartIndex + ":" + contentEndIndex + ":\n'"
                    + nv.toString(contentStartIndex,(int)(elementOffset>>32)));
                    //+ xmlDocument.substring(contentStartIndex, contentEndIndex) + "'");
        }


text:
Q: Interacting with Custom Database Tables in Wordpress I have a custom wordpress table(my_table). And i am inserting,updating all that good stuff to it. When i try to use
$wpdb->get_results("SELECT * FROM $wpdb->my_table",ARRAY_A);

or
$wpdb->get_results("SELECT * FROM my_table",ARRAY_A);

I get this error
WordPress database error: [Table 'mydatabase.my_table' doesn't exist]
SELECT * FROM my_table

I have tried to add my_table to wp-db.php as well but i still receive this error.

*

*Yes the table is in the database

*There is data in the table

Is their a config option of i need to change or somewhere else where i need to add my table name? I cannot find it for some reason.
full error
WordPress database error Table 'mydatabase.mytable' doesn't exist for query SELECT * FROM mytable made by do_action, call_user_func_array, promos

A: Ok tiggles, here is what I would do in your situation if you are still stuck. Create a new table, but this  time, by executing a SQL command from WordPress, using something like :
$wpdb->query('CREATE TABLE mynewtable (First_Name char(50), Last_Name char(50), ... etc.)');

Immediately check that you can query it. If so, then go to your databse and dump all data from mytable into this newly created table. Use this one instead.
If it was a user permission because the user that created the previous table was not the same as the one granted access to as WordPress, then you will be safe.

A: If your table my_table is, indeed, in the mydatabase database and if mydatabase is, indeed, WordPress' database, there is no reason why it should not work. If mydatabase is not WordPress database or if my_table is in another database, then it is normal that it does not work.


text:
Q: How to deduce the area of an equilateral triangle whose inscribed circle has radius $r$? What is the area of an equilateral triangle whose inscribed circle has radius $r$?  I would like to learn how to deduce the formula.
I deduced the circle outside the triangle, so now I tried to do it with the circle inside the triangle, but I haven't arrived to a solution yet.

A: Make a construction like so
Here, $OC = r$, $BC = \frac{l}{2}$, $AB = l$. Since $ABC \sim BOC$, taking ratios, we get $AC = \frac{l^2}{4r}$.
By the Pythagorean theorem,
$AB^2 = AC^2 + BC^2$,
Therefore, $$l = \sqrt{\frac{l^2}{4} + \frac{l^4}{16r^2}}$$
Simplifying, we get $l = r\sqrt{12}$
The area would be $\frac{\sqrt{3}}{4}l^2$, which would be
$$3\sqrt{3}r^2$$

A: Using the circle in SS_C4's answer, We know that triangles BOC and ABC are similar, so both are 30-60-90 triangles.
Applying the properties of 30-60-90 triangles $(r,\,{\sqrt 3}r,\,2r)$: We have, $OC=r,\,BC= {\sqrt 3}r,\,\,\text{and }\,AC={\sqrt 3}({\sqrt 3}r)=3r$
Therefore, the area is $\frac{1}{2}bh=\frac{1}{2}(2BC)(AC)=\frac{1}{2}(2{\sqrt 3}r)(3r)=3{\sqrt 3}r^2$


text:
Q: service doing a periodic job I am developing an Android app which must perform 2 periodic tasks in background:

*

*download files from server every 24 hours.

*perform file operations each week on phone sd card.

How do i do this?

A: Firstly you need to use AlarmManager. When the registered alarm e.g. 24 hours case, will trigger, you can call service from the broadcast receiver of AlarmManager. You need to study a bit about AlarmManager if you don't already know. For further help you can get some idea from code below:
Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1); //+1 For Next day (24 hours or so...)
cal.set(Calendar.HOUR_OF_DAY,  hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));

AlarmManager am = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.cancel(pendingIntent);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

Here is how you can set your Alarm. Now when Alarm will be triggered, you will call your service like this:
public class AlarmReceiver extends BroadcastReceiver
{
   @Override
   public void onReceive(Context arg0, Intent arg1)
   {
           // Call you service or any task here
   }
}

Last thing, don't forget to mention your broadcast receiver and service in AndroidManifest.xml
<receiver android:name=".AlarmReceiver">
</receiver>
<service android:name=".MyService"/>

A: Here's what official android docs says about AlarmManager
Note: The Alarm Manager is intended for cases where you want to have
your application code run at a specific time, even if your application
is not currently running. For normal timing operations (ticks, timeouts, etc)
it is easier and much more efficient to use Handler.

Handler documentation.


text:
Q: How to implement asynchronous rest webservice client using RestTemplate? I want to invoke rest webservice call asynchronously using spring 3.1 rest template. Currently we are using Resttemplate.getForObject method to invoke the rest webservice. Now as per the requirement we have to invoke another webservice method concurrently along with existing one. We are invoking this method call from EJB 2.1 stateless session bean by instantiating the method class.
Sample code is as below:-
public class MyImplServerBean extends EJBObject{
   RestServiceImpl restImpl = new RestServiceImpl();
   ArrayList<User> userDetailsList = restImpl.getUserDetails(123);
}

public class RestServiceImpl {

   RestTemplate template = new RestTemplate();

   public ArrayList<User> getUserDetails(int userId){

   ArrayList<User> userList = new ArrayList<User>();
   String url = "http://localhost:7001/myUserService/userId";
   User user = template.getForObject(url, User.class);
   userList.add(user);
   return userList;
}

We now need to make getUserDetails method call asynchronously. I got the idea using @Async annotation but not aware how to exactly implement.
Can you please help in this.

A: I used this tutorial to accomplish a similar task. I did some modifications. Here is how to get it working.
1) Create a configuration class and make sure it is scanned by ApplicationContext. I use AnnotationConfigWebApplicationContext.
@EnableAsync
@Configuration
public class AsyncConfiguration implements AsyncConfigurer
{
    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        return executor;
    }

    @Override
    public Executor getAsyncExecutor()
    {
        return new ThreadPoolTaskExecutor();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()
    {
        return new CustomAsyncExceptionHandler();
    }
}

2) Annotate your method with
@Async("threadPoolTaskExecutor")

Your method must either return void or Future.
3) Make sure the async method is public and called from another class. This way Spring "sees" the annotation when the method is invoked reflectively.


text:
Q: Django cannot show image I use django in Ubuntu. I set static_url, static_root, media_url and media_root in settings.py like this code.
settings.py
DEBUG = False

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'static','media')

In index.html I set image like this code.
index.html

After that, I use command django-admin collectstatic and open website but it not show image. How to fix it?

A: Use the built-in static tag
{% load static %}

A: Seems like path you given here in src is incorrect,

correct your path and image will be visible to you.


text:
Q: Connect and disconnect from Bluetooth BLE on Windows Phone 8.1 I've got a device that is operated by Windows Phone 8.1 and Android phones. Since only one of these phones can use the device at any time, we need to disconnect from the device as soon as we finished the use.
On Android, the library we use is able to connect and disconnect, but on Windows Phone 8.1 I can only seem to connect, I can't find a way to tell the phone to disconnect from the device. I have to manually unpair the phone from the device,
has anyone been able to disconnect a paired Bluetooth device? If yes, how?
Thank you!

A: Call Dispose() on the GattDeviceService, ensure that all GattCharacteristic objects are null and DON'T unregister ValueChanged event handlers from GattCharacteristic.
Finally call GC.Collect() (Microsoft told that this is a bug in WP8.1 and should be fixed in Win10)

A: If you are communicating through a StreamSocket, a Dispose() call will disconnect.
Depending on your code, a using() statement might be the most elegant way to do so.

A: This may not help with win8 apps, but for anyone working on UWP apps this article is helpful for pairing and unpairing:
https://msdn.microsoft.com/en-us/windows/uwp/devices-sensors/pair-devices
The gist of it is you call DeviceInformation.Pairing.UnpairAsync method. https://msdn.microsoft.com/library/windows/apps/windows.devices.enumeration.deviceinformationpairing.unpairasync
Calling that method pops up the windows dialog asking the user for permission to unpair the device.


text:
Q: this is a code for drawing using tkinter but using laser method in my class gives unexpected results I have written a code that has a class whose methods are called button command. The Problem comes when I use the laser method & I try to zoom in & out but after that if I again call the pen method using button command the cursor is somewhere & line drawn is somewhere else. Plzz help me solve this..
class drawline:
def __init__(self, win):

    self.win = win

    self.canvas = Canvas(self.win, width=1400, height=780, bg="White")
    self.scv = Scrollbar(self.win, orient="vertical")
    self.scv.place(x=1380, y=5, height=780)
    self.sch = Scrollbar(self.win, orient="horizontal")
    self.sch.place(x=0, y=775, width=1400)
    self.scv.config(command=self.canvas.yview)
    self.sch.config(command=self.canvas.xview)

    self.canvas.config(yscrollcommand=self.scv.set,xscrollcommand=self.sch.set)
    self.canvas.create_window(0,0)

    self.canvas.config(scrollregion=self.canvas.bbox('ALL'))

    self.rulep = PhotoImage(file="ruler.png", master=self.win)
    self.rulel = Label(self.win, image=self.rulep)
    self.bx = Button(self.win, text="X", font=('Algerian', 10), bg="White", fg="Red",
                     command=self.rulerforget)
    self.bx.bind('<Enter>', self.ruleun)
    self.bx.bind('<Leave>', self.btfor)
    self.active = None
    self.lastx, self.lasty = self.canvas.canvasx(0), self.canvas.canvasy(0)
    self.canvas.place(x=0, y=0)

def laser(self):
    self.canvas.configure(cursor="hand2")
    self.active = laser_b

    # self.canvas.bind("<MouseWheel>", self.zoomer)
    self.canvas.bind("<Enter>", self.cancel_normal_scroll)
    self.canvas.bind("<Leave>", self.cancel_normal_scroll)

def zoomer(self, e):
    if self.active == laser_b:
        print(e.delta, e.x)

        if e.delta == 120:
            self.canvas.scale("all", e.x, e.y, 1.1, 1.1)
        elif e.delta == -120:
            self.canvas.scale("all", e.x, e.y, 0.9, 0.9)
        self.canvas.configure(scrollregion=self.canvas.bbox('all'))
        self.lastx = self.canvas.canvasx(0)
        self.lasty = self.canvas.canvasy(0)

def cancel_normal_scroll(self, event):
    return "break"

def pen(self):
    self.canvas.bind("<Button-1>", self.xy)
    self.canvas.bind("<B1-Motion>", self.addLine)
    self.canvas.configure(cursor="pencil")
    self.active = pen_b

def xy(self, event):
    if self.active == pen_b:
        self.lastx, self.lasty = event.x, event.y
        print(self.lastx,self.lasty)

def addLine(self, event):
    if self.active == pen_b:
        self.canvas.create_line((self.lastx, self.lasty, event.x, event.y))
        self.lastx, self.lasty = event.x, event.y

def erase(self):
    self.active = erase_b
    self.canvas.bind("<Button-1>", self.xy)
    self.canvas.bind("<B1-Motion>", self.use_eraser)
    self.canvas.configure(cursor="circle")

def use_eraser(self, event):
    if self.active == erase_b:
        self.canvas.create_oval((self.lastx, self.lasty, event.x, event.y), fill="White", outline="White", width=25)
        self.lastx, self.lasty = event.x, event.y
        self.canvas.after(1000, lambda: self.canvas.create_oval((self.lastx, self.lasty, event.x, event.y),
                                                                fill="White", outline="White", width=50))
        self.canvas.after(3000, lambda: self.canvas.create_oval((self.lastx, self.lasty, event.x, event.y),
                                                                fill="White", outline="White", width=100))

def note(self):
    self.active = note_b
    if self.active == note_b:
        self.entry = Text(self.win, bd=0, font=("Purisa", 15), fg="Black", bg="Yellow")
        self.canvas.bind("<ButtonPress-1>", self.text)

def text(self, event):
    if self.active == note_b:
        self.textx = event.x
        self.texty = event.y
        self.entry.place(x=event.x, y=event.y, width=300, height=175)
        self.entry.focus_force()
        self.entry.bind('<Double-Button-1>', self.canvastext)

def canvastext(self, event):
    if self.active == note_b:
        k = self.entry.get(1.0, 'end')
        self.mytext = self.canvas.create_text(self.textx, self.texty, text=k, font=('Algerian', 20))
        self.entry.place_forget()
        self.entry.delete(1.0, 'end')

def myruler(self):
    self.active = ruler_b
    self.rulel.place(x=200, y=200)
    self.rulel.bind('<B1-Motion>', self.on_move)
    self.rulel.bind('<Enter>', self.rulerplace)
    self.rulel.bind('<Leave>', self.btfor)

def rulerplace(self, event):
    if self.active == ruler_b:
        self.bx.place(in_=self.rulel, relx=0.98, rely=0.15)

def ruleun(self, event):
    if self.active == ruler_b:
        self.rulel.unbind('<Leave>')

def btfor(self, event):
    if self.active == ruler_b:
        self.bx.place_forget()

def rulerforget(self):
    if self.active == ruler_b:
        self.rulel.place_forget()
def rectangle(self):
    self.active = shape_b
    self.canvas.configure(cursor="crosshair")
    self.rect = None
    self.canvas.bind("<ButtonPress-1>", self.on_button_press)
    self.canvas.bind("<B1-Motion>", self.on_move_press)
    self.canvas.bind("<ButtonRelease-1>", self.on_button_release)

def on_move(self, event):
    if self.active == shape_b:
        component = event.widget
        locx, locy = component.winfo_x(), component.winfo_y()
        w, h = self.win.winfo_width(), self.win.winfo_height()
        mx, my = component.winfo_width(), component.winfo_height()
        xpos = (locx + event.x) - (15)
        ypos = (locy + event.y) - int(my / 2)
        if xpos >= 0 and ypos >= 0 and w - abs(xpos) >= 0 and h - abs(ypos) >= 0 and xpos <= w - 5 and ypos <= h - 5:
            component.place(x=xpos, y=ypos)

def on_button_press(self, event):
    if self.active == shape_b:
        # save mouse drag start position
        self.start_x = event.x
        self.start_y = event.y
        self.rect = self.canvas.create_rectangle(self.lastx, self.lasty, 1, 1, fill="White", outline="Black")

def on_move_press(self, event):
    if self.active == shape_b:
        curX, curY = (event.x, event.y)

        # expand rectangle as you drag the mouse
        self.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)

def on_button_release(self, event):
    if self.active == shape_b:
        pass


text:
Q: Python 3.0 Pandas converters giving syntax error I am running Jupyter notebook with Python 3.0 using Pandas to read from an Excel file. I am using a converter to change values in columns i.e. -1 to 1. I keep getting a syntax error in the converters.
import pandas as pd

def convert_adult(cell):
    if cell==-1:
        return 1
    return cell

df = pd.read_excel("Merged.xlsx", "Sheet1", converters = ['adult_not_activation':convert_adult])

return is
  File "<ipython-input-17-8eea921e19bb>", line 10
    df = pd.read_excel("Merged.xlsx", "Sheet1", converters = ['adult_not_activation':convert_adult])
                                                                                ^
SyntaxError: invalid syntax

I am in the beginning of my journey in Python and Pandas so I hope my problem is not too trivial to ask. Cheers

A: The error points you to the problem :) You are using a list where a dict is expected.
df = pd.read_excel("Merged.xlsx", "Sheet1", converters = {'adult_not_activation': convert_adult})

A: converters argument takes a dictionary, You are giving this dictionary as a list but with dictionary syntax.
df = pd.read_excel("Merged.xlsx", "Sheet1", converters = {'adult_not_activation':convert_adult}) # {} instead of []


text:
Q: Select columns of specific type in MySQL 4.1 I need to find all smallint (specifically smallint(5)) columns in a MySQL 4.1 database. It seems that INFORMATION_SCHEMA is only available in MySQL 5+. Is there an alternative?
Thanks

A: Here's something that should work for you:
select distinct table_name, column_name, column_type
  from information_schema.columns
  where table_schema = 'THE_DB_YOU_WANT_TO_QUERY'
    and column_type = 'smallint(5)';

Obviously, replace 'THE_DB_YOU_WANT_TO_QUERY' with the actual name of your database. It took me awhile to get all of this to work, but it should work for you.

A: Use the SHOW COLUMNS syntax to return the data you need.

A: I think it should work

SHOW TABLES; # Get list of all tables
DESC [EACH TABLE]; # and then check "Type" column

A: If you are using PHP you could use the following functions to gain information about specific fields in your tables.
mysql_field_type
mysql_fetch_field
mysql_field_len
mysql_field_flags

mysql_fetch_field gives you the most info.
To give you an example of how you might use it:
$SQLquery = 'SELECT * FROM '.$tableName;
$arr;
$field_array = array();
$res = mysql_query($SQLquery);

$numOfCols = mysql_num_fields($res);

for($y=0;$y<=($numOfCols-1);$y++)
{
    $fieldName1 =  mysql_field_name($res, $y);
    $field = mysql_fetch_field($res, $y);
    if($field->max_length < 6 && $field->numeric = true)
    {
      $field_array[] = $fieldName1;
    }
}

I realize this is not a MySql answer but I hope it helps if there is no way to get the info you need via MySql in 4.1


text:
Q: Show view after parsing JSON from multiple URL's I have a table view with two sections
These two sections contains data from two different urls
Im using Alamofire to download content from json.
Url from section 1 has more content than section 2. Both tasks are runnings asynchronously
Once section 2 data has been completed, im reloading table view. But for some reason my section1 data gets terminatted and no results are displayed
Please let me know how to handle that. Below is the sample code structure
let url1 = "https://xxxxxxxxxx.com"
Alamofire.request(url1)
    .responseJSON { response in
        guard let json = response.result.value as? [Any] else {}
        //do parsing from json
        mytableview.reloadData()
    }

let url2 = "https://yyyyyyyyy.com"
Alamofire.request(url2)
    .responseJSON { response in
        guard let json = response.result.value as? [Any] else {}
        //do parsing from json
        mytableview.reloadData()
    }

In my case, data from url2 is fetching and parsing json fast and is reloadingtableview. While doing my url1 is still parsing data
How can I display both url1, url2 data at a time after all the parsing done. Please advice

A: Use a DispatchGroup:
let group = DispatchGroup()

let url1 = "https://xxxxxxxxxx.com"
group.enter()
Alamofire.request(url1)
    .responseJSON { response in
        guard let json = response.result.value as? [Any] else {}
        //do parsing from json
        group.leave()
}

let url2 = "https://yyyyyyyyy.com"
group.enter()
Alamofire.request(url2)
    .responseJSON { response in
        guard let json = response.result.value as? [Any] else {}
        //do parsing from json
        group.leave()
}

group.notify(queue: DispatchQueue.main) {
    mytableview.reloadData()
}


text:
Q: Tailwind Flex Box Responsive Grid with Cards issue Here is where i started with
Preview

Code :

              {error ?
{error.message}
 : null}
              {!isLoading ? (
                users.map(user => {
                  const { username, name, email } = user;
                  return (

{name}

                            {email}

Then i tried to make it more spaced out like shown in the codepen example here :
https://codepen.io/codetimeio/pen/RYMEJe
but everytime i try to add some padding and margin it escapes to the next line and i cant figure out why it does that or how i can stop it

Here is the line i updated :

Here is my tailwind config file
module.exports = {
  theme: {
    container: {
      center: true
    },
    screens: {
      sm: "640px",
      md: "768px",
      lg: "1024px",
      xl: "1280px"
    },
    fontFamily: {
      display: ["Gilroy", "sans-serif"],
      body: ["Graphik", "sans-serif"]
    },
    extend: {}
  },
  variants: {},
  plugins: []
};

I really want to understand what im doing wrong so that i can use tailwind as my main templating framework

Here is updated code as per the given answer below

              {error ?
{error.message}
 : null}
              {!isLoading ? (
                users.map(user => {
                  const { username, name, email } = user;
                  return (

{name}

                            {email}

A: It's happening because of the extra margins, w-1/3 means ~ width: 33.3333% If you add a margin on top of it, three can't fit in one line.
There are alternative ways (widths taking into account the gutter or gap property), but in exactly this case you could just use padding instead of margins, because you already have a presentational wrapping element around your cards.
Example: https://codepen.io/tlgreg/pen/RmLMOx
Not related, but few notes looking at your code:

*

*Unless you use the old color palette in the config, grey-darker will not work.

*img is block by default in v1.

*invisible and lg:visible changes visibility, the header will take up space, if that not what you want, it should be hidden and lg:flex.


text:
Q: Difference between Spring-JPA and Spring-Data-JPA Difference between Spring-JPA and Spring-Data-JPA and I don't mean JPA the specification .
I am new to JPA and Spring.
While integrating Hibernate with Spring as JPA provider i came across two Spring project.
Please clarify the difference as well as relationship between
https://mvnrepository.com/artifact/org.springframework/spring-jpa
https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa
I found out spring-data-jpa contains JpaRepository interface which i intend to use but then what is the use of spring-jpa.

A: If you look at the artifcat dates that is something really old - 2008. You should not worry about it.

A: Essentially, Spring Data is predecessor for Spring Framework: JPA.


text:
Q: Users unable to access Database we have an SQL Server called sql01. On this,we have attached a number of databases, including the SSRS report server, which people can access.
I have created a new database called ToolingSystem and added some data into table in it.
I have also written an application that access this database using the following connection string:
Data Source=sql01;Initial Catalog=ToolingSystem;Integrated Security=True

But no one is able to see the data but me and the people in my IT group. Is there something I need to do in order to allow people to connect to this server/database (I don't know which).
They are getting a "Login failed for user 'username'".
What i'm looking for is people in our domain to see this information.
It seems they can see the server (like the reporting stuff) but not my new database
I created a user for the database and am using it in the connection string but its still not letting me log in.

A: What you need is:

*

*A Login for the User at Server Level (Should already exist if people
work with other databases on this Server)

*A user in your new db, which is mapped to the login

example: when you have windows authentication as login for your users, it can look like this:
USE yourDB
GO

CREATE USER [JohnDoe] FOR LOGIN [YOURDOMAIN\John.Doe]

[JohnDoe] the can be added to the roles he needs (db_datareder, whatever...)

A: Here is a script to set up login, user, role, grant rights.  I like to match the user name to the domain name, so it's obvious what is going on.  This requires square brackets.  This method will allow your users to connect directly to the database with excel if they have network access to it.  You can look into application roles to restrict those shenanigans, I think.
CREATE LOGIN [DOMAIN\UserGroup] from WINDOWS;
USE ToolingSystem;;
CREATE USER [DOMAIN\UserGroup] from LOGIN [DOMAIN\UserGroup];
CREATE ROLE ToolingSystemUserRole;
exec sp_addrolemember 'db_datareader','ToolingSystemUserRole';
--exec sp_addrolemember 'db_otherroles','ToolingSystemUserRole';

exec sp_addrolemember 'ToolingSystemUserRole','DOMAIN\UserGroup];


text:
Q: How to move the curstor to a selected UIText Field in IOS Programming? I have created a login page with Login and Clear Button.  If the clear button is pressed the text field should clear but i need the cursor, back to username textfield but it remains in Password Field. Can anyone suggest answer for this?

A: In your clear method implement this:
[myTextField becomeFirstResponder];

A: Use UIResponder's -becomeFirstResponder method:
[usernameField becomeFirstResponder];

A: you can use like this
  -(void)yourclearMethod:(UIButton*)sender{

   [username_textfield becomeFirstResponder];
   }


text:
Q: What information can we extract from the electronic band structure? I have some difficulty in understanding the electronic band structure.I want know that for a 3D crystal,what information can I extract from its complicated band structure,for example the band structure of the SiC(I downloaded this figure from google).And what intuition that I can build for such a complicated band structure?

A: The most useful information you can extract from the band structure for an insulator like SiC involves: (1) the value of the bandgap (the energy difference between the highest occupied band--the valence band--and the lowest unoccupied band--the conduction band); (2) the direct or indirect nature of the band gap (direct if the valence band max occurs at the same k point as the conduction band minimum, and indirect otherwise); and (3) the band dispersion or the slope of the bands involved in the band gap--steeper slopes indicate stronger orbital interactions and faster carrier mobility, on the other hand an ionic crystal will have very flat bands.


text:
Q: clean exit - waiting for changes before restart? please tell me how to solve this problem why doesnt it start and say restarting
         const express = require('express');
         const mongoose = require("mongoose");
         const app = express();
         const port = 3000;
                 app.post("/employee/add",(req,res)=>{
                     console.log("request is here");

                 })

        mongoose.connect("mongodb://localhost:27017//class-project")
            .then(()=>{
             app.listen(port),()=> {
             console.log('Server is listening on port ${port}');
             }
            })

A:    mongoose.connect("mongodb://localhost:27017//class-project")
            .then(()=> {
              app.listen(port, ()=> console.log('Server is listening on port ${port}');
            })


text:
Q: Calculating the time of a Brachistochrone I derived the general equation of a Brachistochrone, which is a cycloid.
$y=A(1-\cos\theta)$
$x=A(\theta-\sin\theta)$
I'm now trying to calculate the time needed to go from the origin to a point $(x,y)$.
From previous analysis I found that the time is equal to
$T=\sqrt{\frac{1}{2g}}\int_0^x\sqrt{\frac{1+(y')^2}{y}}dx$
I'm struggling to solve this. This is what I found so far
$\frac{dx}{d\theta}=A(1-\cos\theta)$
$\frac{dy}{d\theta}=A\sin\theta$
Applying the chain rule: $\frac{dy}{dx}=\frac{dy}{d\theta}\frac{d\theta}{dx}=\frac{A\sin\theta}{A(1-\cos\theta)}=\frac{\sin\theta}{1-\cos\theta}$
Therefore, $(\frac{dy}{dx})^2=(\frac{\sin\theta}{1-\cos\theta})^2$
Therefore,
$T=\sqrt{\frac{1}{g}}\int_0^x\sqrt{\frac{1-\cos^2\theta}{(1-\cos\theta)^2}}d\theta$
Is this right? How do I go on from here? I have the coordinates of two points (and therefore I could derive the equation of the brachistochrone curve between them) and I would like to find the time taken to fall from the initial to the final point along the brachistochrone under acceleration g. Thank you!

A: Changing variables from $x$ to $\theta$ via $x=A(\theta - \sin\theta)$, the integral that represents the time to go from $(x,y)=(0,0)$ to $(x_0,y_0)$ becomes
$$
T=\sqrt{\frac 1{2g}}\int_{\theta=0}^{\theta_0}\sqrt{\frac{1+(y')^2}y}\frac{dx}{d\theta}\,d\theta
$$
where $\theta_0$ is the value of $\theta$ that corresponds to $x_0$. You've calculated $y'=\sin\theta/(1-\cos\theta)$ and $dx/d\theta=A(1-\cos\theta)$ correctly, now plug everything in. The integral will simplify to
$$
T=\sqrt{\frac A{2g}}\int_{\theta=0}^{\theta_0}\sqrt{\frac{(1-\cos\theta)^2+\sin^2\theta}{1-\cos\theta}}\,d\theta=\sqrt{\frac Ag}\int_{\theta=0}^{\theta_0}\sqrt{\frac{1-\cos\theta}{1-\cos\theta}}\,d\theta=\sqrt{\frac Ag}\theta_0.
$$

A: From $ x = A(\theta - \sin\theta) $ and $ y = A(1 - \cos\theta) $ we have:
$$ v = \frac{ds}{d\theta} = \sqrt{\left(\frac{dx}{d\theta}\right)^2 + \left(\frac{dy}{d\theta}\right)^2}  = A\sqrt{(1 - \cos\theta)^2 + (\sin\theta)^2} = A\sqrt{(2(1 - \cos\theta)} = \sqrt{2Ay}$$
By the law of conservation of energy we get:  $$ \frac{ds}{dt} = v = \sqrt{2gy}  . $$
Therefore: $$ \frac{d\theta}{dt} = \frac{\frac{ds}{dt}}{\frac{ds}{d\theta}} = \frac{\sqrt{2gy}} {\sqrt{2Ay}} = \sqrt{\frac{g}{A}} \quad \text{and} \quad T = \int_0^\theta\sqrt{\frac{A}{g}} \mathrm{d}t = \sqrt{\frac{A}{g}}·\theta $$


text:
Q: NFS client shows everything as nobody:nogroup I am on Ubuntu Server, one server running nfs-kernel-server, and the other mounting the NFS export.  On the client, when I use ls -l or stat, everything shows as nobody:nogroup, but the actual permissions are used/respected.
Is this normal?  If so, why is this the case?

A: If you're using NFSv4, it might be rpc.idmapd that's either missing, not running or incorrectly configured. It needs to contain correct domains and realms. You can also set the default nobody user to something else if you'd like. See idmapd.conf .
Please specify protocol version and export options next time, so that the answer may be more relevant :-)

A: I upgraded from Jaunty 9.04 to Precise 12.04.
Precise seems to use NFSv4 as default. I used ages finding out this, -- the fix was for me to change fstab on every client:
aasen:/nmu/home /home nfs rsize=8192,wsize=8192,timeo=14,intr

to:
aasen:/nmu/home /home nfs vers=3,timeo=14,intr

And now the users and groups are shown.
If you are really using nfsv4 and wanting to do that, this is obviously not your fix, but others might search, come to this question and be happy with this answer :-)

A: yes, by default nfs server has root_squash on which makes client access nobody:nogroup. you can turn that off (less security) if you want during the export.


text:
Q: How to make fixed menu bar so that it doesn't move when resizing the browser window I would like to make my menu bar have a fixed positioning so that when the browser window is resized, the menu doesn't move. I also would it to work for all browsers. I have done a bit of answer browsing however the solutions i have seen doesn't seem to work for me.
Here's my code:
CSS
#nav ul {
    padding:0px;
    height:37px;
    position: fixed;
    top: -12px;
    left: 850px;
}

.nav li {
    margin:0px;
    list-style: none;
}

#nav li, #nav .last {
    float:left;
}

#nav a {
    text-decoration: none;
    text-transform:uppercase;
    width:auto;
    font-weight:bold;
    height:auto;
    padding: 85px 10px 5px;
    height:18px;
    color:#3a434e;
    font-size:12px;
    float:left;
}

#ie7 #nav a, #ie6 #nav a {
    font-size:9px;
    padding:11px 8px 5px;
}

#nav li:hover a, #nav .active a {
    color:#4D4D4D!important;
    background-image:url(../imgs/nav_active.gif);
    background-position:right center;

    -moz-border-radius-bottomright: 5px;
    -moz-border-radius-bottomleft: 5px;
    -webkit-border-bottom-right-radius: 5px;
    -webkit-border-bottom-left-radius: 5px;
}

#nav li:hover a {
    color:#FFF!important;
    background-color: #C1272D;
}

HTML:

Home

Basket

Lightbox

My Account

Contact us

Admin

Logout

A: Either set a width in a percentage that will be based off the viewport width. Or set both right and left values.
   left: distance from left;
   right: distance from right;


text:
Q: How to create a falsy sentinel object in Python? I have a function which is designed to be called by passing in one of to keyword arguments. I'm using a sentinel object as default value, so that I can make sure no one just calls func() without any arguments, which is a clear logical error. It is ok to call the function by passing None as a value for one of the arguments, in those cases it just doesn't do any processing.
NO_VALUE = object()

def func(*, arg1 = NO_VALUE, arg2 = NO_VALUE):
    if arg1 is NO_VALUE and arg2 is NO_VALUE:
        raise ValueError("Pass in one of `arg1` or arg2`.")

    if arg1 is not NO_VALUE and arg1:
        # Do something with a truthy `arg1` value.
    if arg2 is not NO_VALUE and arg2:
        # Do something with a truthy `arg2` value.

Could I somehow easily make NO_VALUE be falsy, so that I could simplify the if arg1 is not NO_VALUE and arg1 and if arg2 is not NO_VALUE and arg2 to just if arg1 and if arg2 respectively?
I tried making NO_VALUE an empty tuple () but it seems that the id() of an empty tuple is always(?) same as the id() of any other empty tuple. I also don't want to make NO_VALUE e.g. an empty list object, since then I'd get linter warnings about using a mutable default value.

A: In any case: for a Python object to be "Falsy" it can be an instance of a class which implements __bool__ and returns False when that is called:
class FalsySentinel:
    def  __bool__(self):
        return False

NO_VALUE = FalsySentinel()

def func(*, arg1 = NO_VALUE, arg2 = NO_VALUE):
    if arg1 is NO_VALUE and arg2 is NO_VALUE:
        raise ValueError("Pass in one of `arg1` or arg2`.")

    if arg1:
        # Do something with a truthy `arg1` value.
    if arg2:
        # Do something with a truthy `arg2` value.

There are other ways to produce falsy objects, like objects that implement __len__ and return 0 on it - but this is the most explicit and straightforward way.

A: To get the behavior you describe, I think you should use kwargs instead of keyword args. Consider the following function:

def func(**kwargs):
    if kwargs.keys() == set(['arg1']):
        print(kwargs['arg1'])
    elif kwargs.keys() == set(['arg2']):
        print(kwargs['arg2'])
    else:
        raise ValueError("Pass in one of `arg1` or `arg2`")

Because you're ultimately trying to achieve more complicated logic on your function arguments, it makes sense to handle this with code, as opposed to letting the compiler try to sort it out with weird sentinels.


text:
Q: Prevent CentOS re-enabling user quotas after reboot/power failure I have a client that has an internal server in their office for their Intranet.
Their office recently been through some power cuts in their area recently. Whenever the power goes back on, the server will boot up, and the user quotas will be reset to a default. This is causing problems when their staff are uploading to their Intranet because they have exceeded their quota.
Every time this happens, I disable the quotas, but this gets enabled when the server reboots.
How can I permanently disable quotas, including when the server reboots?
The server is running CentOS 6.6.
Here's the contents of /etc/fstab

A: Remove grpquota,usrquota, from the entry for /home in your /etc/fstab file.  That will permanently disable quota usage on the volume in question.


text:
Q: Why doesn't my @media screen save I have been stuck with this problem or the past hour and its really annoying me. I am making my website responsive to different screen sizes every time I write the code for it, I test it and it works. Then if I close the browser and reopen or reopen the code editor (brackets) the page loads like nothing happened. So I have re write everything again. This problem keeps recurring and I don't know why it wont just save. I can place my code since its over 2000 lines and I have just moved on to the responsive side of the site.
but I have applied this to every html file.
<meta name="viewport" content="width=device-width, initial-scale=1.0">

and I have used this as my starting statement for the @media in the css
@media screen and (max-width:)

CSS
header img{
    margin-left: auto;
    margin-right: auto;
    display: block;
}

footer img{
    position:fixed;
    margin-left: auto;
    margin-right: auto;
    display: block;
    bottom: 5%;
    left: 40%;
    right: 40%;
}

.logo img{
    position:fixed;
    margin-left: auto;
    margin-right: auto;
    display: block;
    bottom: 2%;
    left: 40%;
    right: 40%;

}

.home img{
    position:fixed;
    margin-left: auto;
    margin-right: auto;
    display: block;
    bottom: 5%;
    left: 40%;
    right: 40%;
    width: 120px;
}

.socialmedia-twitter img {
    position:fixed;
    margin-left: auto;
    margin-right: auto;
    display: block;
    bottom: 5%;
    left: 20%;
    right: 40%;
}

.socialmedia-facebook img {
    position:fixed;
    margin-left: auto;
    margin-right: auto;
    display: block;
    bottom: 5%;
    right: 20%;
    left: 40%;
}

@media screen and (max-width: 640px){

    header img{
        margin-left: auto;
        margin-right: auto;
        display: block;
    }

    footer img{
        position:fixed;
        margin-left: auto;
        margin-right: auto;
        display: block;
        bottom: 5%;
        left: 40%;
        right: 40%;
    }

    .logo img{
        position:fixed;
        margin-left: auto;
        margin-right: auto;
        display: block;
        bottom: 2%;
        left: 40%;
        right: 40%;
    }

    .home img{
        position:fixed;
        margin-left: auto;
        margin-right: auto;
        display: block;
        bottom: 5%;
        left: 40%;
        right: 40%;
        width: 120px;
    }

    .socialmedia-twitter img {
        position:fixed;
        margin-left: auto;
        margin-right: auto;
        display: block;
        bottom: 5%;
        right: 50%;

    }

    .socialmedia-facebook img {
        position:fixed;
        margin-left: auto;
        margin-right: auto;
        display: block;
        bottom: 5%;
        right: 20%;
        left: 50%;
    }

}

A: There are lots of reasons why this could have happen, but i think it is the obvious one.
if you reach a sertan width @media screen and (max-width: 640px)
this css wil be enabled, in order to work his way back you need to define the width your working in.
While working on the design, it is also recommended to turn of any cache methods.
So for this to work proberly you will prob need three @media screen properties.
Examples


text:
Q: redirect url to phar archive I have created an archive file for my web app with script below :
   <?php
$phar = new Phar('appdepot.phar', 0, 'appdepot.phar');
$phar->buildFromIterator(
    new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator(dirname(__FILE__).'/depot0/', FilesystemIterator::SKIP_DOTS)),
    dirname(__FILE__).'/depot0');
$phar->setStub($phar->createDefaultStub("index.php"));

and I run my phar file through  :
    <?php

include("appdepot.phar")

?>

the index page is loaded and is redirect to login page but I have not found error

Not Found

The requested URL /depot/login/login_id.php was not found on this
  server.

how can I redirect all urls inside web app to phar (I think this is the work of stub file??)


text:
Q: For a linear operator,T, show the existence of a polynomial, p, such that p(T) is a nilpotent operator I am faced with the following (homework) problem.
Given an operator $T : C^{n} \rightarrow C^{n}$, show that there exists a polynomial $p(z) \in C$ of degree at most $n - 1$ such that $p(T)$ is a nilpotent operator.
Unfortunately, I am unsure about how to approach this problem. Can anyone give me some clues?

A: Not to put too fine a point on it, but except for trivialities, this cannot be the case as stated.  Counterexample:   consider the linear map $T:C^2 \to C^2$ such that
$T(z_1, z_2)^T = (\lambda_1 z_1, \lambda_2 z_2)^T, \tag{1}$
where $\lambda_1, \lambda_2 \in C$, $\lambda_1 \ne \lambda_2$, and $\lambda_1 \ne 0 \ne \lambda_2$.  In matrix form, we have
$T = \begin{bmatrix} \lambda_1 & 0 \\ 0 & \lambda_2 \end{bmatrix}.\tag{2}$
Any polynomial  $p(z) \in C[z]$, $\deg p(z)) \le 1$,  may be written in the form $p(z) = az + b$ for $a,b \in C$; thus $p(T) = aT + b$.  Then, from (2),
$aT + b = \begin{bmatrix} a \lambda_1 + b & 0 \\ 0 & a \lambda_2 + b \end{bmatrix}. \tag{3}$
If $aT + b$ were nilpotent, then we would have $(aT + b)^n = 0$ for some ingeter $n \ge 2$.  Then (3) yields
$0 = (aT + b)^n = \begin{bmatrix} (a \lambda_1 + b)^n & 0 \\ 0 & (a \lambda_2 + b)^n \end{bmatrix}, \tag{3}$
forcing
$a \lambda_1 + b = a \lambda_2 + b = 0. \tag{4}$
Now if we allow $a = 0$, (4) becomes $b = 0$, so $aT + b = 0$, which is not nilpotent in any non-trivial sense.  If $a \ne 0$, then (4) forces $\lambda_1 = \lambda_2$, a contradiction.
This simple counterexample shows that such polynomials with $p(T)$ nilpotent cannot exist in general without further conditions on $T$.
I hope this helps sort things out.  Cheers,
and as always,
Fiat Lux!!!


text:
Q: Java Binary Translator Im looking for some help on this binary translator problem. The question goes: In this exercise, you'll write a binary to text translator!
As we've seen, every character can be represented by a string of 8 bits, or a byte. For example, the binary string 010000012 has the decimal value of 6510, which maps to the character 'A'.
So far I have this but the output is: H
                                      CÞ*
                                      NÒ)MØ
Here is my code:
public class Scratchpad extends ConsoleProgram
{
    public void run()
    {
        System.out.println(binaryToText("0100100001001001"));
        System.out.println(binaryToText("010000110110111101100100011001010100100001010011"));
        System.out.println(binaryToText("010011100110100101100011011001010010000001001010011011110110001000100001"));
    }

    public String binaryToText(String binary)
    {
        String s2 = "";
        char nextChar;

        for(int i = 0; i <= binary.length()-8; i += 9) //this is a little tricky.  we want [0, 7], [9, 16], etc (increment index by 9 if bytes are space-delimited)
        {
            nextChar = (char)Integer.parseInt(binary.substring(i, i+8), 2);
            s2 += nextChar;
        }
        return s2;
    }

    public int binaryToDecimal(String binaryString)
    {
        int decimal = 0;
            int base    = 2;
            for (int i = binaryString.length() - 1; i >= 0; i--) {
                if (binaryString.charAt(i) == '1')
                    decimal += Math.pow(base,i);
            }
            return decimal;
    }
}

A: Here is the solution:
For each string of bits, perform the following:

*

*Create an array of 256 chars, the value of each element is the ASCII value of the index.  For example, the value of element 65 is the character 'A'.  This is the translationTable referenced below.

*If the length of the string of bits is divisible by 8, continue.

*If the string of bits contains only digits 0 and 1, continue.

*Split the string of bits into smaller strings, each of which is exactly 8 digits in length.

*For each 8-bit string, convert from binary to decimal.

*Using the translationTable, convert from decimal to the desired ASCII character.

*Accumulate the individual characters into a string (perhaps using a StringBuilder).

A: public class Scratchpad extends ConsoleProgram
{

    public String binaryToText(String binary)
    {
        String s2 = "";
        char nextChar;

        for(int i = 0; i <= binary.length()-8; i += 8)
        {
            nextChar = (char)Integer.parseInt(binary.substring(i, i+8), 2);
            s2 += nextChar;
        }
        return s2;

    public int binaryToDecimal(String binaryString)
    {
        int numPlaces = binaryString.length();

        int currentExponent = numPlaces - 1;

        int decimalValue = 0;

        for(int i = 0; i < binaryString.length(); i++)
        {

            int placeValue = (int) Math.pow(2, currentExponent);

            char currentDigit = binaryString.charAt(i);
            int digitValue = Character.getNumericValue(currentDigit);

            System.out.print(digitValue + " * (" + placeValue + ")");
            if(i != binaryString.length() - 1)
            {
                System.out.print(" + ");
            }

            decimalValue += digitValue * placeValue;

            currentExponent--;
        }

        System.out.println(" = " + decimalValue);

        return decimalValue;
    }
}


text:
Q: mySQL sytem to grade marks reading from a database and choosing subject of two trying to develop a system to assign grades to students. The system reads marks from my database, and assigns a grade after getting average of scores.
Used case statements, keep throwing errors. So i tried if statements but its giving me issues.  Someone know a better way to do it?
delimiter //

create function assign_grade(v_idnumber int)
returns varchar(50) deterministic
begin

  declare v_marks1 varchar(50);
  declare v_marks2 varchar(20);
  declare phyz varchar(50);
  declare Chem varchar(50);
  declare grade varchar(50);

  set phyz = (select Physics from marks where Sid=v_idnumber);
  set Chem=(select Chemistry from marks where Sid=v_idnumber);

  if(phyz>Chem)
  begin
   set v_marks1=(select(English+Kisw+Math+Physics+Bio+Business+Geog+Cre)/8 from marks where Sid=v_idnumber);

   if (v_marks1>= 80 && v_marks1<=100) then
            set grade ='A';
                else if (v_marks1>=60&& v_marks1<=79)
                    set grade='B';
                else if (v_marks1>=40&& v_marks1<=59)
                    set grade ='C';
                else if (v_marks1>=30&& v_marks1<=49)
                    set grade ='D';
                else if (v_marks1>=0&& v_marks1<=29)
                   set grade ='E';
                else
                    set grade = 'Failed Miserably';

             end if
             end if
             end if
             end if
             end if

             return grade;

    end;

     if(Chem>phyz)
           begin
            set v_marks2=(select(English+Kisw+Math+Chemistry+Bio+Business+Geog+Cre)/8 from marks where Sid=v_idnumber);
       if (v_marks2>= 80 && v_marks2<=100) then
            set grade ='A';
                else if (v_marks2>=60&& v_marks2<=79)
                    set grade='B';
                else if (v_marks2=40&& v_marks2<=59)
                    set grade ='C';
                else if (v_marks2>=30&& v_marks2<=49)
                    set grade ='D';
                else if (v_marks2>=0&& v_marks2<=29)
                   set grade ='E';
                else
                    set grade = 'Failed Miserably';

             end if
             end if
             end if
             end if
             end if

             end;

             return grade;

  //

A: For start, You want just optimize your function
(I'm not expert in your language (I think is Vb right?) ):
set phyz = (select Physics from marks where Sid=v_idnumber);
set Chem = (select Chemistry from marks where Sid=v_idnumber);

if(phyz>Chem)
    set v_marks=(select(English+Kisw+Math+Physics+Bio+Business+Geog+Cre)/8 from marks where Sid=v_idnumber);
else /*if (Chem > phyz) I comment the "if" for treatment where chem > phyz and Chem == phyz */
    set v_marks=(select(English+Kisw+Math+Chemistry+Bio+Business+Geog+Cre)/8 from marks where Sid=v_idnumber);
end if

/* You have just one same treatment for all types (phyz > chem ; chem >phyz, etc...)
   When you optimize you code, verify your code isn't duplicate :-)
*/

if (v_marks>= 80 && v_marks<=100)
    set grade = 'A';
else if (v_marks>=60 && v_marks<=79)
    set grade = 'B';
else if (v_marks>=40 && v_marks<=59)
    set grade = 'C';
else if (v_marks>=30 && v_marks<=49)
    set grade = 'D';
else if (v_marks>=0 && v_marks<=29)
    set grade = 'E';
else
    set grade = 'Failed Miserably';
end if

return grade;


text:
Q: Unable to access the methods from one class to another class in android Unable to access the methods from one class to another class in android.
Actually, what I am trying is
ClassA.java
class ClassA extends Activity
{
    method_1();
}

ClassB.java
class  ClassB extends BroadCastReciever
{
    // I need to access the method_1 from the class ClassA.
}

How can I do this?

A: inside ClassA  declare public method from ClassB create object of ClassA and access method using object
 write below code inside ClassB
Like
ClassA  classa = new ClassA();
classa.method_1();

Note :

*

*if possible don't create class as static if it is not necessary.

*provide class modifier to public.

A: First Solution
Declare your method1() as follows -
public static void method_1()
{

}

Then you can access it from ClassB as follows -
ClassA.method1();

Second Solution
Create an object of ClassA and access method1() from ClassB as follows-
ClassA classA = new ClassA();
classA.method1();

EDIT:
If both the classes are in the same package then you can use protected instead of public in the First Solution.

A: there is two way to access it
1) you need to create method as public static method() so that you can access it anywhere by calling class name dot method name like Aaa.method();
2)or you need a object to call method like passing Aaa's object to broadcast class and call method on it.
EDIT:
if you are passing context from activity A to brodcast class then you can convert context into activity object to call its public methods.
like:
in brodcast class:
((yourActivityName)context).method();

A: mark method_1(); as public and static
Eg:
class ClassA extends Activity
{
    public void static method_1();
}

Then you should be able to access method_1(); without creating a object of class A.

A: i guess you cant access a method from a class that extends an activity in android , however you can add an inner or helper class to the activity class like this example :
Call a public method in the Activity class from another class?

A: Basically you can call any method from another class, as long as it's public. If the method is static, you don't even need to instantiate it. But read some tutorials to get the basic idea of OOP instead of just looking for a solution for your specific problem, it'll help a lot more!

A: You should never be able to to that ... How do you know if the activity is still alive? The best way to send messages from BroadcastReceivers to Activities (where you register a custom receiver in onCreate/onresume and unregister in onDestroy/onPause) is to send another broadcast message from BroadcastReceiver.
But you could catch the initial broadcast already in activity. Consider using OrderedBroadcastReceivers.


text:
Q: Is there a way to ensure a request is coming from a trusted UI application? So to give you a background, we have a backend application that has a huge number of APIs (Spring boot framework). And then there is a UI application with a mix of React and Ember.js. We are using OAuth2.0 access token.
Each page of the UI may use a number of API resources and permissions of the pages (including actions and buttons) are managed separately than permissions for accessing APIs directly.
Now the issue is that in order to stop anyone with their access token can directly call any API. To stop that, we decided to link the services/resources used in each page or a button to the route url (Ember.js routes) so that based on the user's permission to those routes, we determine whether they have access to particular service in the backend or not. In other words, if a user sends a request to a service directly and say that service is linked to a page that he doesn't have access to in the UI world, then security check stop him.
However, this is now becoming a headache. The pages are constantly changing, some services are being removed or new services are added and we have to continously maintain the SQL scripts to keep the linkage between the two. Now to mention that due to hierarchical structure of the UI (routes) this has become even more complicated.
Now I was wondering, if we could determine that a request is coming from a UI then we don't need to check the permission to API and given the UI won't be rendered if they don't have access to it, we can safely let the request comes in and served. And if the same user uses his UI token to access the API directly we simply block it. If a user need direct access to an API, then they have to get a special token used for API (Some user may need to use API directly for their).
Now the question is how can we determine the request is from UI and that UI page is the one we trust? I did a search in internet but couldn't really find anything any framework or protocol for this. Is it even possible?

A:
how can we determine the request is from UI and that UI page is the one we trust?

You probably can't. To do this you'd need a trusted execution environment, in other words, one in which the user is not in total control. Examples of this are credit card point of sale machines, cable/satellite TV boxes, and the ARM TrustZone. These environments allow you to store a secret on the client device that isn't visible to the user. You can then use this secret to communicate with your code in the trusted environment without the user having access to it.
Your user's web browser however, is not a trusted execution environment. The user can see all the cookies, local and session storage, etc on your web page and they can use them to make requests directly via something like curl such that the requests look the same as ones from the browser.
Not in the question, but what SHOULD you do?
It's sounds like it might be a pain given how you have things set up now, but do all your security and permissioning on the API. If you don't want users to use their tokens to call the API a ton in an automated way, then implement rate limiting on the tokens.
It may also be useful to revisit the reasons why you have this setup in the first place. Are users calling the API directly overloading servers? Is it just a UX concern around what the user sees on the page? Is it an access concern around what data and actions the user has access to?

A: Sorry if I've totally missed it, but isn't this just a simple case of Cross-Origin Resource Sharing (CORS)?
You'd set the allowed CORS on each controller to be that of your UI/frontend domain.
@CrossOrigin(value = "example.com")
@RestController
public class PrivateController {

}

The controller will now reject anything that doesn't come from example.com.


text:
Q: Typescript: clean code remove or decrease if's Hello I have the following code, where I need to do many checks of calls from the database:
 public execute = async ({
    contract_id,
    matricula,
    parent_id,
    patrimony_code,
    product_id,
    serial_number,
    type,
  }: AssignProductDTO): Promise<Either<AppError, ProductInstance>> => {
    //verify type
    if (!(type in ProductTypes)) throw new Error(`${type}, is invalid`);
    //instance checks
    const hasInstance = await this.instanceRepository.bySN(serial_number);
    if (hasInstance) {
      throw new Error(
        `This ${serial_number} product has already been assigned `,
      );
    }
    const parentInstance = parent_id
      ? await this.instanceRepository.byId(parent_id)
      : null;
    if (parentInstance === undefined) {
      throw new Error(`Parent Instance dont exist.`);
    }
    //products checks
    const hasProduct = await this.productRepository.byId(product_id);
    if (!hasProduct) throw new Error(`This product dont exist.`);
    //employee checks
    const hasEmployee = await this.employeeRepository.byMatricula(matricula);
    if (!hasEmployee) throw new Error(`This Employee dont exist.`);
    const employeeHasProduct = await this.instanceRepository.hasInstance(
      product_id,
      hasEmployee.id,
    );
    if (employeeHasProduct) {
      throw new Error(
        `The enrollment employee: ${matricula} already has an instance of the product.`,
      );
    }
    //stock checks
    const stock = await this.stockRepository.byContractAndProduct(
      contract_id,
      product_id,
    );
    if (!stock) {
      throw new Error(
        `The product has no stock, or the contract has no supply.`,
      );
    }
    if (stock.quantity <= 1) {
      throw new Error(`The stock of this product is less than or equal to 1`);
    }
  };

But this became a very ugly code, but I'm not getting a solution on how to refactor so much if, because they are essential checks for the logic.
I would be very grateful if someone could give me tips on how I can refactor this in a cleaner way.


text:
Q: Get persian information from android Geocoder I'm trying to get Persian information from android Geocoder, i mean i pass latitude and longitude and i want to get name of the city in Persian, but there is no locale to get those info in Persian.
I can see that in Place Autocomplete google suggests location names in Persian, but there's no locale to set for the Geocoder.
Does anybody know a way to get those info in Persian?

A: Pass your desire locale in constructor:
Geocoder geo = new Geocoder(getActivity(), new Locale("fa"));

A: Update : for geocoding package :
 List<Placemark> _placemarks =
     await placemarkFromCoordinates(
         latitude,
         longitude,
         localeIdentifier: "fa-IR"
     );


text:
Q: Exclude children of custom post type from search I have a custom post type of 'location'. I then have children pages for each of the pages for that cpt. so it looks something like this, "www.example.com/location/location-name/child-page/", each child page is using a post template of "location-product-services.php". So what I am trying to do is exclude from the search results the children of this cpt.
I am trying to do it by checking the meta data to see if it is using that template. I just cant seem to get it working. Any help would be great.
This is what I currently have -
// Exclude local product and services pages from search result.
function location_subpages_exclude_search( $query ) {
    if ( is_search() && !is_admin()) {
        $query->set('meta_query',
            array(
                'key' => '_wp_page_template',
                'value' => 'location-product-services.php',
                'compare' => '!='
            )
        );
    }
}

add_action('pre_get_posts', 'location_subpages_exclude_search');

Thanks in advance.

A: First, I pretty much exclusively use the Relevanssi plugin any time I want to modify search. But to search programmatically, I think this is what you're after:
$taxonomy = 'location';
$terms = get_terms($taxonomy, array( 'parent' => 0, 'search' => $query ) );

if ( $terms && !is_wp_error( $terms ) ) :
?>

        <?php foreach ( $terms as $term ) { ?>

<a href="<?php echo get_term_link($term->slug, $taxonomy); ?>"><?php echo $term->name; ?>

        <?php } ?>

<?php endif;?>

Use the function get_terms to search your CPT, the 'search' is your $query (you might consider wrapping the search string with the SQL wildcard '%') and 'parent'=>0 returns only the top level.

A: I figured it out.
First I got all parent pages of my post type, used get_pages() grab them all.
Looped through each of the parent pages and ran another get_pages() for children of that parent.
function SearchFilter($query) {

    if ($query->is_search) {

        $args = array(
            'hierarchical' => 0,
            'post_type' => 'location',
            'parent' => 0, //returns all top level pages
            'post_per_page' => -1
        );

        $parents = get_pages($args);
        $excludes = array();

        foreach($parents as $parent) :
            $args = array(
                'post_type' => 'location',
                'child_of' => $parent->ID,
                'post_per_page' => -1
            );
            $children = get_pages($args);
            foreach($children as $child):
                array_push($excludes, $child->ID);
            endforeach;
        endforeach;

        $query->set('post__not_in', $excludes);
    }
    return $query;
 }
 add_filter('pre_get_posts','SearchFilter');


text:
Q: How can I snapshot the state of my Google App Engine application and upload it to a separate Google Cloud Storage? I am setting up a relationship where two Google App Engine applications (A and B) need to share data. B needs to read data from A, but A is not directly accessible to B. Both A and B currently use Google Datastore (NOT persistent disk).
I have an idea where I take a snapshot of A's state and upload it to a separate Google Cloud Storage location. This location can be read by B.
Is it possible to take a snapshot of A using Google App Engine and upload this snapshot (perhaps in JSON) to a separate Google Cloud Storage location to be read from by B? If so, how?

A: What you're looking for is the Datastore managed export/import service:

This page describes how to export and import Cloud Firestore in
  Datastore mode entities using the managed export and import service.
  The managed export and import service is available through the gcloud
  command-line tool and the Datastore mode Admin API (REST,
  RPC).

You can see a couple of examples described in a bit more details in these more or less related posts:

*

*Google AppEngine Getting 403 forbidden trying to update cron.yaml

*Transferring data from product datastore to local development environment datastore in Google App Engine (Python)
You may need to take extra precautions:

*

*if you need data consistency (exports are not atomic)

*to handle potential conflicts in entity key IDs, especially if using manually-generated ones or referencing them in other entities

If A is not directly accessible to B isn't actually something intentional and you'd be OK with allowing B to access A then that's also possible. The datastore can be accessed from anywhere, even from outside Google Cloud (see How do I use Google datastore for my web app which is NOT hosted in google app engine?). It might be a bit tricky to set it up, but once that's done it's IMHO a smoother sharing approach than the export/import one.


text:
Q: URLDecoding requests I am trying to get the original url from requests. Here is what I have so far:
res = requests.get(...)
url = urllib.unquote(res.url).decode('utf8')

I then get an error that says:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 60-61: ordinal not in range(128)

The original url I requested is:
https://www.microsoft.com/de-at/store/movies/american-pie-pr\xc3\xa4sentiert-nackte-tatsachen/8d6kgwzl63ql

And here is what happens when I try printing:
>>> print '111', res.url
111 https://www.microsoft.com/de-at/store/movies/american-pie-pr%C3%A4sentiert-nackte-tatsachen/8d6kgwzl63ql
>>> print '222', urllib.unquote( res.url )
222 https://www.microsoft.com/de-at/store/movies/american-pie-präsentiert-nackte-tatsachen/8d6kgwzl63ql
>>> print '333', urllib.unquote(res.url).decode('utf8')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 60-61: ordinal not in range(128)

Why is this occurring, and how would I fix this?

A: UnicodeEncodeError: 'ascii' codec can't encode characters

You are trying to decode a string that is Unicode already. It raises AttributeError on Python 3 (unicode string has no .decode() method there). Python 2 tries to encode the string into bytes first using sys.getdefaultencoding() ('ascii') before passing  it to .decode('utf8') which leads to UnicodeEncodeError.
In short, do not call .decode() on Unicode strings, use this instead:
print urllib.unquote(res.url.encode('ascii')).decode('utf-8')

Without .decode() call, the code prints bytes (assuming a bytestring is passed to unquote()) that may lead to mojibake if the character encoding used by your environment is not utf-8. To avoid mojibake, always print Unicode (don't print text as bytes), do not hardcode the character encoding of your environment inside your script  i.e., .decode() is necessary here.

There is a bug in urllib.unquote() if you pass it a Unicode string:
>>> print urllib.unquote(u'%C3%A4')
ä
>>> print urllib.unquote('%C3%A4') # utf-8 output
ä

Pass bytestrings to unquote() on Python 2.