问:
TypeScript custom transformers with ts.createWatchProgram
TypeScript has several high-level APIs to implement watch/compile,  for example:

createWatchCompilerHost( rootFiles, options, system, ... )

createSolutionBuilderWithWatchHost( system, ... )

createSolutionBuilderWithWatch( host, rootFiles, ... )

Can any of them be used with custom transformers?

A comment to solutionBuilder.getNextInvalidatedProject() mentions ability to pass transformers, but it cannot be used with watchers.

Basically, I need via API to run TypeScript compiler in --watch mode, but passing in my custom transformers. Any clues?

答:
Better approach, more aligned with solutionBuilder.getNextInvalidatedProject() recommendation.

When you call solutionBuilder.getNextInvalidatedProject() .emit(...) manually, you can pass in transformers. Invoking that API marks build as complete, meaning it won't emit again in its usual non-customised way.

You would invoke it both before the initial build() and from WatchStatusReporter callback.

That way you inject custom transformers, yet still retain built-in watching logic. See the proof-of-concept script below at work:

Here's full code, see also Gist and Repl.it.

// @ts-check

var ts = require('typescript');

var tsconfig_json = JSON.stringify({
  compilerOptions: {
    outFile: __filename + '.out.js',
    allowJs: true,
    checkJs: true,
    target: 'es3'
  },
  files: [__filename]
}, null, 2);

var s = {
  delete: 3
};

/** @type {import('typescript').System} */
var sysOverride = {};
for (var k in ts.sys) { sysOverride[k] = ts.sys[k]; }
sysOverride.readFile = function (file) {
  if (ts.sys.resolvePath(file) === ts.sys.resolvePath(__dirname + '/tsconfig.json')) {
    // console.log('readFile(', file, ') -> overridden tsconfig_json');
    return tsconfig_json;
  }
  else {
    var result = ts.sys.readFile(file);
    // if (!/node_modules/.test(file))
    //   console.log('readFile(', file, ') -> ' + (typeof result === 'string' ? '"' + result.length + '"' : typeof result));
    return result;
  }
};
sysOverride.writeFile = function (file, content) {
  console.log('  sys.writeFile(', file, ', [', content.length, '])');
  ts.sys.writeFile(file, content);
};

var host = ts.createSolutionBuilderWithWatchHost(
  sysOverride,
  void 0,
  reportDiag,
  reportDiag,
  reportWatch);

var buildStart = Date.now();

var solutionBuilder = ts.createSolutionBuilderWithWatch(
  host,
  [__dirname],
  { incremental: false }, {});

initiateFirstBuild();

function initiateFirstBuild() {
  var firstBuild = solutionBuilder.getNextInvalidatedProject();
  if (firstBuild) {
    buildStart = Date.now();
    startBuild(firstBuild);
  }

  solutionBuilder.build();
}

/**
 * @param {import('typescript').InvalidatedProject<import('typescript').EmitAndSemanticDiagnosticsBuilderProgram>} proj
 * @param {import('typescript').Diagnostic=} watchDiag
 */
function startBuild(proj, watchDiag) {
  ts.sys.write(
    '\x1b[93m ' + (ts.InvalidatedProjectKind[proj.kind] + '          ').slice(0, 10) + '\x1b[0m' +
    (watchDiag ? '' : '\n'));

  if (watchDiag) reportDiag(watchDiag);

  buildStart = Date.now();

  if (proj && proj.kind === ts.InvalidatedProjectKind.Build) {
    progSource = proj;
    proj.emit(
      void 0,
      void 0,
      void 0,
      void 0,
      { after: [transformInjectStatementNumbers] });
  }

}

function completeBuild(watchDiag) {
  ts.sys.write('\x1b[90m ' + (((Date.now() - buildStart) / 1000) + 's        ').slice(0, 10) + '\x1b[0m');
  if (watchDiag) reportDiag(watchDiag);
}

/** @type {import('typescript').FormatDiagnosticsHost} */
var diagHost;
/** @param {import('typescript').Diagnostic} diag */
function reportDiag(diag) {
  if (!diagHost) {
    diagHost = {
      getCanonicalFileName: function (fileName) {
        return ts.sys.resolvePath(fileName)
      },
      getCurrentDirectory: function () {
        return ts.sys.getCurrentDirectory();
      },
      getNewLine: function () {
        return ts.sys.newLine;
      }
    };
  }

  var output = ts.sys.writeOutputIsTTY && ts.sys.writeOutputIsTTY() ?
    ts.formatDiagnosticsWithColorAndContext([diag], diagHost) :
    ts.formatDiagnostic(diag, diagHost);

  output = output.replace(/^[\r\n]+/, '').replace(/[\r\n]+$/, '');

  ts.sys.write(output + '\n');
}

/** @param {import('typescript').Diagnostic} diag */
function reportWatch(diag) {
  var proj = solutionBuilder.getNextInvalidatedProject();
  if (proj && /** @type {*} */(proj).getProgram) {
    progSource = /** @type {*} */(proj);
  }

  if (proj)
    startBuild(proj, diag);
  else
    completeBuild(diag);
}

/** @type {{ getProgram(): import('typescript').Program }} */
var progSource;
/** @type {import('typescript').TypeChecker} */
var checker;
/** @param {import('typescript').TransformationContext} context */
function transformInjectStatementNumbers(context) {
  checker = progSource.getProgram().getTypeChecker();
  return transformFile;

  function transformFile(sourceFile) {
    console.log('   transforming(', sourceFile.fileName, ')...');
    return ts.updateSourceFileNode(
      sourceFile,
      sourceFile.statements.map(decorateStatementWithComplexityAndType));
  }
}

/**
 * @param {import('typescript').Statement} statement
 */
function decorateStatementWithComplexityAndType(statement) {
  var nodeCount = 0;
  var type;
  ts.forEachChild(statement, visitStatementChild);

  return ts.addSyntheticLeadingComment(
    statement, ts.SyntaxKind.SingleLineCommentTrivia,
    ' INJECTED >> complexity: ' + nodeCount +
    (!type ? '' : ' : ' + checker.typeToString(type)));

  /**
   * @param {import('typescript').Node} child
   */
  function visitStatementChild(child) {
    nodeCount++;
    if (!type) type = checker.getTypeAtLocation(child);
    if (type.getFlags() === ts.TypeFlags.Any) type = null;
    ts.forEachChild(child, visitStatementChild);
  }
}

```


来源: stackexchange

问:
multiply 2 time discrete vectors using numpy library (python)
I need to Write a function with the next inputs:

n1, x1, n2, x2 and the function return two outputs n, y.

n1 is discrete time array of the signal x1. (Discrete time means that the sample of time are integer). n2 is discrete time array of the signal x2. x1 and x2 are the values of a signal (such as sin or cos for example). The purpose of the defined function is the multiply between two signals. y[n] = x[n1] · x[n2]

basically i need to multiply two time discrete vectors: for example : X1=[1,2,3,4] x2=[1,1,1,1]

n1=[-3,-2,-1,0] n2=[0,1,2,3]

vectors n1, n2 are the time vectors witch meet at the time 0. and X1, x2 are their values(amplitude) .

I need to multiply them the answer should be the vector for the time :[-3,-2,-1,0,1,2,3]

the vector of amplitude: [0,0,0,1,0,0,0] because thay meet just in time 0.

need to use numpy library functions.
and didn't succeed doing so

please help.

答:
You say you would like to multiply them, but your desired result does not show a multiplication.
Do you mean to say the vector y should contain ones for those values where n1 and n2 "meet", and zeros otherwise?

Will vectors n1 and n2 always contain ordered consecutive integers, as in your example?

--

Once clarified, here is a solution:

```<code>n = np.arange(n1[0], n2[-1] + 1)
y = np.zeros(n.size)
y[-n2.size: n1.size] += 1
</code>```

First, arange creates an array of consecutive integers from the first element of n1 to the last element of n2, under the assumption that n1 contains lower elements than n2.
An array of zeros is created, and finally one is added (+= 1) to the elements between the size of n2 starting from the end, and the size of n1 starting from the beginning.

ContentLicense: CC BY-SA 4.0

Body:
You say you would like to multiply them, but your desired result does not show a multiplication.
Do you mean to say the vector y should contain ones for those values where n1 and n2 "meet", and zeros otherwise?

Will vectors n1 and n2 always contain ordered consecutive integers, as in your example?

--

Once clarified, here is a solution:

n = np.arange(n1[0], n2[-1] + 1)
y = np.zeros(n.size)
y[-n2.size: n1.size] += 1

First, arange creates an array of consecutive integers from the first element of n1 to the last element of n2, under the assumption that n1 contains lower elements than n2.
An array of zeros is created, and finally one is added (+= 1) to the elements between the size of n2 starting from the end, and the size of n1 starting from the beginning.


问:
What causes SignalR to receive net::ERR_CONNECTION_RESET on connect?
I have a simple SingulaR example that I've added to a legacy ASP.Net MVC application.

Here are the various parts:

OWIN Startup class

```<code>[assembly: OwinStartup(typeof (Startup))]

namespace MyApp.Web
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}
</code>```

SignalR Hub

```<code>using System.Collections.Generic;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace MyApp.Web
{
    [HubName("podService")]
    public class PodServiceHub : Hub
    {
        public PodServiceHub()
        {
            ;
        }

        public IEnumerable<string> GetMessages()
        {
            return new[] {"blah", "blah", "blah"};
        }
    }
}
</code>```

Server-side facade

```<code>using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace MyApp.Web
{
    public class PodService
    {
        PodService(IHubConnectionContext<dynamic> clients)
        {
            Clients = clients;
        }

        public PodService()
            : this(GlobalHost.ConnectionManager.GetHubContext<PodServiceHub>().Clients)
        {
        }

        IHubConnectionContext<dynamic> Clients { get; set; }

        public void SendMessageToClient(string message)
        {
            Clients.All.doSomething(message);
        }
    }
}
</code>```

Portions of startup Javascript:

```<code>    var podService = $.connection.podService;

...

    $.extend(podService.client, {
        doSomething: function(message) {
            console.log("received message:" + message);
        }
    });

    // test
    $.connection.hub.start()
        .done(function() {
            podService.server.getMessages()
                .done(function(messages) {
                    console.log("received message:" + message);
                });
        });
</code>```

Within one of the controllers called by the first page:

```<code>_podService.SendMessageToClient("Hello from the server!");
</code>```

Upon executing the application, the following error is displayed in the console of Chrome's dev tools:

WebSocket connection to 'ws://localhost:62025/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=02LJFqBcRBWKXAOlaSwgMPWG0epV7AFl19gNjFCvA0dxD2QH8%2BC9V028Ehu8fYAFN%2FthPv65JZKfK2MgCEdihCJ0A2dMyENOcdPkhDzEwNB2WQ1X4QXe1fiZAyMbkZ1b&connectionData=%5B%7B%22name%22%3A%22podservice%22%7D%5D&tid=6' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

After this error, however, the podService.server.getMessages() returns with the message from the server printing ["blah", "blah", "blah"] to the console and subsequently the doSomething client function is invoked printing "received message: Hello from the server!".

The calls from both the client and the server are transmitting data, so this error doesn't appear to be breaking the app.  It definitely seems to be an issue though.  The code above was based upon the sample code generated by the Microsoft.AspNet.SignalR.Sample NuGet package which doesn't display the same behavior.  The only difference I'm aware of between my example and NuGet-based sample is that I've added this to a legacy MVC app vs. a pure OWIN-based app.  Based upon a comment I read on this SO question this shouldn't be an issue.

So, what's wrong with this example usage and/or what could be causing the connection reset?

答:
In my Case I was using

```<code>string sqlConnectionString = ConfigurationManager.ConnectionStrings["GAFI_SignalR"].ConnectionString;
GlobalHost.DependencyResolver.UseSqlServer(sqlConnectionString);
</code>```

The problem was accessing the database when the user didin't have permission to connect to the database.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple SingulaR example that I've added to a legacy ASP.Net MVC application.

Here are the various parts:

OWIN Startup class

[assembly: OwinStartup(typeof (Startup))]

namespace MyApp.Web
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

SignalR Hub

using System.Collections.Generic;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace MyApp.Web
{
    [HubName("podService")]
    public class PodServiceHub : Hub
    {
        public PodServiceHub()
        {
            ;
        }

        public IEnumerable<string> GetMessages()
        {
            return new[] {"blah", "blah", "blah"};
        }
    }
}

Server-side facade

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace MyApp.Web
{
    public class PodService
    {
        PodService(IHubConnectionContext<dynamic> clients)
        {
            Clients = clients;
        }

        public PodService()
            : this(GlobalHost.ConnectionManager.GetHubContext<PodServiceHub>().Clients)
        {
        }

        IHubConnectionContext<dynamic> Clients { get; set; }

        public void SendMessageToClient(string message)
        {
            Clients.All.doSomething(message);
        }
    }
}

Portions of startup Javascript:

    var podService = $.connection.podService;

...

    $.extend(podService.client, {
        doSomething: function(message) {
            console.log("received message:" + message);
        }
    });

    // test
    $.connection.hub.start()
        .done(function() {
            podService.server.getMessages()
                .done(function(messages) {
                    console.log("received message:" + message);
                });
        });

Within one of the controllers called by the first page:

_podService.SendMessageToClient("Hello from the server!");

Upon executing the application, the following error is displayed in the console of Chrome's dev tools:

WebSocket connection to 'ws://localhost:62025/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=02LJFqBcRBWKXAOlaSwgMPWG0epV7AFl19gNjFCvA0dxD2QH8%2BC9V028Ehu8fYAFN%2FthPv65JZKfK2MgCEdihCJ0A2dMyENOcdPkhDzEwNB2WQ1X4QXe1fiZAyMbkZ1b&connectionData=%5B%7B%22name%22%3A%22podservice%22%7D%5D&tid=6' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

After this error, however, the podService.server.getMessages() returns with the message from the server printing ["blah", "blah", "blah"] to the console and subsequently the doSomething client function is invoked printing "received message: Hello from the server!".

The calls from both the client and the server are transmitting data, so this error doesn't appear to be breaking the app.  It definitely seems to be an issue though.  The code above was based upon the sample code generated by the Microsoft.AspNet.SignalR.Sample NuGet package which doesn't display the same behavior.  The only difference I'm aware of between my example and NuGet-based sample is that I've added this to a legacy MVC app vs. a pure OWIN-based app.  Based upon a comment I read on this SO question this shouldn't be an issue.

So, what's wrong with this example usage and/or what could be causing the connection reset?

Body:
In my Case I was using

string sqlConnectionString = ConfigurationManager.ConnectionStrings["GAFI_SignalR"].ConnectionString;
GlobalHost.DependencyResolver.UseSqlServer(sqlConnectionString);

The problem was accessing the database when the user didin't have permission to connect to the database.


问:
Add conditions on my ajax request (if and else)
How can add conditions on my ajax request?
When I add the code on below is active just for only one. </p>

<pre class="lang-js prettyprint-override"><code>$.ajax({
  type: 'GET',
  url: urlPost,
  success: function (data) {
    $.each(data, function (key, value) {
      createPostItem(value.name, value.image, value.size);
      if (value.size == 'post') {
        $('#img-size').addClass("img-post")
      } else {
        $('#img-size').addClass("img-story")
      }
    });
  }
});
</code>```

答:
(I use a Tailwind css)

My ajax request:

```<code>var urlPost = "assets/js/imgStock.json"
$.ajax({
type: 'GET',
url: urlPost,
success: function (data) {
    $.each(data, function (key, value) {
        createPostItem(value.name, value.image, value.madeFor, value.size);
        if(value.size == 'story'){
            $('.img-size').css("height", "472")
            $('.img-size').css("height", "270")

        } else {
            $('.img-size').css("height", "270px")

            $('.img-size').css("width", "270px")

        }
        // $('#'+value.size).addClass("img-post")
    });
}
</code>```

});

function to create html:

```<code>function createPostItem(name,image, madeFor, size) {
var html = '<div class="imgStock w-full border-4 my-auto border-blue-500 lg:mx-2 mt-4 mx-auto">' +
    '<div class="flex post text-gray-200 animate__animated animate__fadeIn">' +
    '<div class="img-size mx-auto relative transition duration-300 ease-in transform hover:-translate-y-2">' +
    '<img class="rounded shadow-2xl" src="' + image + '" alt="' + name + '"' +
    '<div class="btn-i absolute ">' +
    '<div class="btn-i absolute text-center pt-2 animate__animated animate__fadeInLeft pl-2">' + name + '</div>' +
    '<span class="flex absolute font-semibold tracking-wide justify-center absolute-pill px-1 text-xxs bg-yellow-400 text-gray-900 rounded-full text-xs">' + madeFor + '</span>' +
    '</div>' +
    '</div>' +
    '</div>' +
    '</div>';

$(".images-array").append(html);
</code>```

}

Doc Json:
 [
  {
    "name": "Calendrier Sofiane Boufal",
    "image": "img/Boufal_Story.jpg",
    "size": "story",
    "madeFor": "Asala Finances"
  },
  {
    "name": "Cover fictive rap",
    "image": "img/Roshi_Cover.jpg",
    "size": "post",
    "madeFor": "Captain Roshi"
  },
  {
    "name": "Calendrier Jean-Pierre Nsame",
    "image": "img/mars_nsame.jpg",
    "size":  "story",
    "madeFor": "Asala Finances"
  },
  {
    "name": "Anniveraire Houboulang Mendes",
    "image": "img/Mendes-Birthday.jpg",
    "size":  "story",
    "madeFor": "Asala Finances"
  }
]

i edit my conditions (if, else) for add the css on the class, i had the same id for multiples images you were right but i still does not work /:

result (:my value.size == "story" are the biggests images (name: calendrier southampton, calendrier young boys, and happy birthday)

enter image description here

Body:
How can add conditions on my ajax request?
When I add the code on below is active just for only one.

$.ajax({
  type: 'GET',
  url: urlPost,
  success: function (data) {
    $.each(data, function (key, value) {
      createPostItem(value.name, value.image, value.size);
      if (value.size == 'post') {
        $('#img-size').addClass("img-post")
      } else {
        $('#img-size').addClass("img-story")
      }
    });
  }
});

Body:
(I use a Tailwind css)

My ajax request:

var urlPost = "assets/js/imgStock.json"
$.ajax({
type: 'GET',
url: urlPost,
success: function (data) {
    $.each(data, function (key, value) {
        createPostItem(value.name, value.image, value.madeFor, value.size);
        if(value.size == 'story'){
            $('.img-size').css("height", "472")
            $('.img-size').css("height", "270")

        } else {
            $('.img-size').css("height", "270px")

            $('.img-size').css("width", "270px")

        }
        // $('#'+value.size).addClass("img-post")
    });
}

});

function to create html:

function createPostItem(name,image, madeFor, size) {
var html = '<div class="imgStock w-full border-4 my-auto border-blue-500 lg:mx-2 mt-4 mx-auto">' +
    '<div class="flex post text-gray-200 animate__animated animate__fadeIn">' +
    '<div class="img-size mx-auto relative transition duration-300 ease-in transform hover:-translate-y-2">' +
    '<img class="rounded shadow-2xl" src="' + image + '" alt="' + name + '"' +
    '<div class="btn-i absolute ">' +
    '<div class="btn-i absolute text-center pt-2 animate__animated animate__fadeInLeft pl-2">' + name + '</div>' +
    '<span class="flex absolute font-semibold tracking-wide justify-center absolute-pill px-1 text-xxs bg-yellow-400 text-gray-900 rounded-full text-xs">' + madeFor + '</span>' +
    '</div>' +
    '</div>' +
    '</div>' +
    '</div>';

$(".images-array").append(html);

}

Doc Json:
 [
  {
    "name": "Calendrier Sofiane Boufal",
    "image": "img/Boufal_Story.jpg",
    "size": "story",
    "madeFor": "Asala Finances"
  },
  {
    "name": "Cover fictive rap",
    "image": "img/Roshi_Cover.jpg",
    "size": "post",
    "madeFor": "Captain Roshi"
  },
  {
    "name": "Calendrier Jean-Pierre Nsame",
    "image": "img/mars_nsame.jpg",
    "size":  "story",
    "madeFor": "Asala Finances"
  },
  {
    "name": "Anniveraire Houboulang Mendes",
    "image": "img/Mendes-Birthday.jpg",
    "size":  "story",
    "madeFor": "Asala Finances"
  }
]

i edit my conditions (if, else) for add the css on the class, i had the same id for multiples images you were right but i still does not work /:

result (:my value.size == "story" are the biggests images (name: calendrier southampton, calendrier young boys, and happy birthday)

enter image description here


问:
Java/Scala BigInteger Pasting
I have a problem with the Java BigInteger class: I can't paste a large value into BigInteger. For example, let's say I want to assign a BigInteger to this number:

26525285981219105863630848482795
```

<p>I cannot assign it directly, because the compiler thinks it's an integer:</p>

<pre class="lang-scala prettyprint-override"><code>val bi = 26525285981219105863630848482795 //compile error
</code>```

But I want it to be a BigInteger. Is there any way to be able to directly paste this into the source code?

If there is no such way, then is there a way in Scala, which has a much easier to use BigInt class?

Title: Java/Scala BigInteger Pasting

Body:
I have a problem with the Java BigInteger class: I can't paste a large value into BigInteger. For example, let's say I want to assign a BigInteger to this number:

26525285981219105863630848482795

I cannot assign it directly, because the compiler thinks it's an integer:

val bi = 26525285981219105863630848482795 //compile error

But I want it to be a BigInteger. Is there any way to be able to directly paste this into the source code?

If there is no such way, then is there a way in Scala, which has a much easier to use BigInt class?

Body:
Starting in Scala 3, and improvements brought to numeric literals, you can use the following form:

val big: BigInt = 26525285981219105863630848482795
// 26525285981219105863630848482795

or even:

val big: BigInt = 26_525_285_981_219_105_863_630_848_482_795
// 26525285981219105863630848482795


问:
How do you check the amount of options in a selector class using javascript?
I need to write a function to check the number of options in a selector tag using javascript. The only thing is I cannot use jQuery (My script is based on puppeteer and web scraping). If you have any suggestions please leave them down below.
Example:

I need the function to return 2 in this example.

Thanks.

答:
You can use children property to extract option from select

document.getElementById('size').children you will get HTMLCollection which consists of all the option present inside that select

To get the count
document.getElementById('size').children.length

You cannot iterate over HTMLCollection to perform an action

You need to convert the HTMLCollection to Array in order to perform an action

Array.from(document.getElementById('cars').children)


问:
PHP foreach statement split names MySQL database
I have a PHP script which interacts with my MySQL database. In my database I've got multiple columns, like:

'temp_0_state',
'temp_0_color',
'temp_1_state',
'temp_1_color',
'temp_2_state',
'temp_2_color'
etc etc. till
'temp_50_state',
'temp_50_color'

All 50 records contain under the 'temp_xxx_state' a name or will be empty ("") and
under 'temp_xxx_color' a color.

I can show all the colors of the 50 records manually, like

```<code>  if ($user['temp_0_state'] == "") {
  } else {
     echo . $user['temp_0_color'] . ;
     }
  if ($user['temp_1_state'] == "") {
  } else {
     echo . $user['temp_1_color'] . ;
     }
  if ($user['temp_2_state'] == "") {
  } else {
     echo . $user['temp_2_color'] . ;
     }
</code>```

etc etc till

```<code>  if ($user['temp_50_state'] == "") {
  } else {
     echo . $user['temp_50_color'] . ;
     }
</code>```

But it'll be easier, and to reduce the amount of php code, to use a foreach statement on the number in the middle of the column name for all records between 0 and 50 (0 < n < 50).
How can I split the names and use a foreach statement on the number 0 till 50 between the underscores?

答:
I did not tested but you can give a try this:</p>

```<code>for ($x = 0; $x <= 50; $x++) {

    $column = 'temp_'.$x.'_state';
    $color  = 'temp_'.$x.'_color';
    if ($user[$column] == "") {

    } else {
        echo $user[$color];
    }

}
</code>```

Body:
I have a PHP script which interacts with my MySQL database. In my database I've got multiple columns, like:

'temp_0_state',
'temp_0_color',
'temp_1_state',
'temp_1_color',
'temp_2_state',
'temp_2_color'
etc etc. till
'temp_50_state',
'temp_50_color'

All 50 records contain under the 'temp_xxx_state' a name or will be empty ("") and
under 'temp_xxx_color' a color.

I can show all the colors of the 50 records manually, like

  if ($user['temp_0_state'] == "") {
  } else {
     echo . $user['temp_0_color'] . ;
     }
  if ($user['temp_1_state'] == "") {
  } else {
     echo . $user['temp_1_color'] . ;
     }
  if ($user['temp_2_state'] == "") {
  } else {
     echo . $user['temp_2_color'] . ;
     }

etc etc till

  if ($user['temp_50_state'] == "") {
  } else {
     echo . $user['temp_50_color'] . ;
     }

But it'll be easier, and to reduce the amount of php code, to use a foreach statement on the number in the middle of the column name for all records between 0 and 50 (0 < n < 50).
How can I split the names and use a foreach statement on the number 0 till 50 between the underscores?

Body:
I did not tested but you can give a try this:

for ($x = 0; $x <= 50; $x++) {

    $column = 'temp_'.$x.'_state';
    $color  = 'temp_'.$x.'_color';
    if ($user[$column] == "") {

    } else {
        echo $user[$color];
    }

}


问:
Getting error messages from QtCreator when trying to build hello world program but the code can still be executed
Im doing another QtCreator setup on a new system, and now Im getting errors when I try to build even a hello world program.Seems something is wrong with my C++ libs of how Qt is trying to put them together. I'm truly stumped here, any suggestions at all are appreciated.

Looked at this a bit more, and it is even stranger than i thought. There is build errors on several lines of several of my projects, but they are actually building and can be ran and even debugged! Unknown type name errors on almost every Qt type, but it still works fine.

So I know even less about the issue: many errors, but everything runs fine....

Anyone seen this before?

答:
Try with QDebug it is much more easy

```<code>#include <QDebug>

int main(int argc, char *argv[]) {
    qDebug() << "hello beautiful world!" << endl << endl;

    return 0;

}
</code>```

Body:
Try with QDebug it is much more easy

#include <QDebug>

int main(int argc, char *argv[]) {
    qDebug() << "hello beautiful world!" << endl << endl;

    return 0;

}


问:
I've downloaded Apache POI, but when I try to use it my code doesn't compile
I've recently download poi-src-3.2-FINAL from poi.apache.org. Now I can't write these:

```<code>import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.extractor.*;
</code>```

Now I can't use the classes of HWPFDocument and WordExtractor.  I can only

```<code>import org.apache.*;
</code>```

Did I forget to download any other thing?

答:
"src" usually indicates a package containing only the source code, not the compiled classes. Check to see if there is a "bin" download available for you.

Update: the binary release is indeed named poi-bin-3.2-FINAL, here is a download link.

OwnerDisplayName: Hamed

LastEditorDisplayName: Eddie

Body:
I've recently download poi-src-3.2-FINAL from poi.apache.org. Now I can't write these:

import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.extractor.*;

Now I can't use the classes of HWPFDocument and WordExtractor.  I can only

import org.apache.*;

Did I forget to download any other thing?

OwnerDisplayName: matt b

ContentLicense: CC BY-SA 2.5


问:
Is it possible to call/use instance attributes or global variables from a custom loss function using Keras?
I would like to define a loss function like the following:

```<code>def custom_loss_function(y_true, y_pred):
    calculate loss based on y_true, y_pred and self.list_of_values
</code>```

where variable self.list_of_values is modified outside this function every iteration and therefore, will have different values each time the custom_loss_function is "called". I know from this post that the loss function is called only once, and then "a session iteratively evaluates the loss".

My doubt is whether it is possible to work with global/external variables (with dynamic values) from the loss function that is then used like this:

```<code>model.compile(loss=custom_loss_function, optimizer=Adam(lr=LEARNING_RATE), metrics=['accuracy'])
</code>```

答:
Specifying the solution here (Answer Section) even though it is present in Comments Section, for the benefit of the Community.

The Variable, list_of_values can be considered as an Input Variable like

list_of_values = Input(shape=(1,), name='list_of_values') and define the Custom Loss function as shown below:

```<code>def sample_loss( y_true, y_pred, list_of_values ) :
    return list_of_values * categorical_crossentropy( y_true, y_pred )
</code>```

Also, the same Global Variable can be passed as an Input to the Model like:

```<code>model = Model( inputs=[x, y_true, list_of_values], outputs=y_pred, name='train_only' )
</code>```

Complete code for an example is shown below:

```<code>from keras.layers import Input, Dense, Conv2D, MaxPool2D, Flatten
from keras.models import Model
from keras.losses import categorical_crossentropy

def sample_loss( y_true, y_pred, list_of_values ) :
    return list_of_values * categorical_crossentropy( y_true, y_pred )

x = Input(shape=(32,32,3), name='image_in')
y_true = Input( shape=(10,), name='y_true' )
list_of_values = Input(shape=(1,), name='list_of_values')
f = Conv2D(16,(3,3),padding='same')(x)
f = MaxPool2D((2,2),padding='same')(f)
f = Conv2D(32,(3,3),padding='same')(f)
f = MaxPool2D((2,2),padding='same')(f)
f = Conv2D(64,(3,3),padding='same')(f)
f = MaxPool2D((2,2),padding='same')(f)
f = Flatten()(f)
y_pred = Dense(10, activation='softmax', name='y_pred' )(f)
model = Model( inputs=[x, y_true, list_of_values], outputs=y_pred, name='train_only' )
model.add_loss( sample_loss( y_true, y_pred, list_of_values ) )
model.compile( loss=None, optimizer='sgd' )
print model.summary()
</code>```

For more information, please refer this Stack Overflow Answer.

Hope this helps. Happy Learning!

Body:
I would like to define a loss function like the following:

def custom_loss_function(y_true, y_pred):
    calculate loss based on y_true, y_pred and self.list_of_values

where variable self.list_of_values is modified outside this function every iteration and therefore, will have different values each time the custom_loss_function is "called". I know from this post that the loss function is called only once, and then "a session iteratively evaluates the loss".

My doubt is whether it is possible to work with global/external variables (with dynamic values) from the loss function that is then used like this:

model.compile(loss=custom_loss_function, optimizer=Adam(lr=LEARNING_RATE), metrics=['accuracy'])

Body:
Specifying the solution here (Answer Section) even though it is present in Comments Section, for the benefit of the Community.

The Variable, list_of_values can be considered as an Input Variable like

list_of_values = Input(shape=(1,), name='list_of_values') and define the Custom Loss function as shown below:

def sample_loss( y_true, y_pred, list_of_values ) :
    return list_of_values * categorical_crossentropy( y_true, y_pred )

Also, the same Global Variable can be passed as an Input to the Model like:

model = Model( inputs=[x, y_true, list_of_values], outputs=y_pred, name='train_only' )

Complete code for an example is shown below:

from keras.layers import Input, Dense, Conv2D, MaxPool2D, Flatten
from keras.models import Model
from keras.losses import categorical_crossentropy

def sample_loss( y_true, y_pred, list_of_values ) :
    return list_of_values * categorical_crossentropy( y_true, y_pred )

x = Input(shape=(32,32,3), name='image_in')
y_true = Input( shape=(10,), name='y_true' )
list_of_values = Input(shape=(1,), name='list_of_values')
f = Conv2D(16,(3,3),padding='same')(x)
f = MaxPool2D((2,2),padding='same')(f)
f = Conv2D(32,(3,3),padding='same')(f)
f = MaxPool2D((2,2),padding='same')(f)
f = Conv2D(64,(3,3),padding='same')(f)
f = MaxPool2D((2,2),padding='same')(f)
f = Flatten()(f)
y_pred = Dense(10, activation='softmax', name='y_pred' )(f)
model = Model( inputs=[x, y_true, list_of_values], outputs=y_pred, name='train_only' )
model.add_loss( sample_loss( y_true, y_pred, list_of_values ) )
model.compile( loss=None, optimizer='sgd' )
print model.summary()

For more information, please refer this Stack Overflow Answer.

Hope this helps. Happy Learning!


问:
Android Drag and DRop Auto Scroll
I'm trying to figure out how to auto scroll a scrollview when a user drags an item to the edge of the screen. I'm really not getting the behavious I expect out of this code. Does anyone have an example or a technique that works?

I have this in my:

```<code>onDrag(View v, DragEvent e)
{
   case DragAction.Location:

    var currentPosition = (int)e.GetX();

    var point = GetTouchPositionFromDragEvent(v, e);

    System.Diagnostics.Debug.WriteLine($"DragAction.Location from {v.GetType()} => {currentPosition}");
    System.Diagnostics.Debug.WriteLine($"DragAction.GLOBAL   from {v.GetType()} => {point.X}");

    if (point.X > App.AppScreenWidth - 50)
    {
        _hostScrollView.ScrollToAsync(_hostScrollView.ScrollX + 30, 0, true);
    }

    if (point.X < 50)
    {
        _hostScrollView.ScrollToAsync(_hostScrollView.ScrollX - 30, 0, true);
    }
}

public static Point GetTouchPositionFromDragEvent(View item, DragEvent e)
{
    Rect rItem = new Rect();
    item.GetGlobalVisibleRect(rItem);
    return new Point(rItem.Left + (int)Math.Round(e.GetX()), rItem.Top + (int)Math.Round(e.GetY()));
}
</code>```

This also has the knock on effect of only scrolling in one direction strangely and also requires the user to keep moving the item in order to fire the events which leads me to think this is entirely the wrong place to be even trying to do this scrolling.

Any pointers or nudges in the right direction would be really appreciated.

答:
In your Activity

```<code>public class MainActivity : AppCompatActivity, View.IOnDragListener,View.IOnScrollChangeListener
</code>```
```<code>private int mScrollDistance;
</code>```
```<code> ScrollView _hostScrollView= FindViewById<ScrollView>(Resource.Id.xxx);
_hostScrollView.SetOnScrollChangeListener(this);
</code>```
```<code>public bool OnDrag(View v, DragEvent e)
        {
            var action = e.Action;

            var scrollView = v as ScrollView;

            switch (action)
            {
                case DragAction.Started:

                    break;
                case DragAction.Location:

                        int y = Java.Lang.Math.Round(e.GetY());
                        int translatedY = y - mScrollDistance;
                        int threshold = 50;
                        // make a scrolling up due the y has passed the threshold
                        if (translatedY < threshold)
                        {
                            // make a scroll up by 30 px
                            scrollView.ScrollBy(0, -30);
                        }
                        // make a autoscrolling down due y has passed the 500 px border
                        if (translatedY + threshold > 500)
                        {
                            // make a scroll down by 30 px
                            scrollView.ScrollBy(0, 30);
                        }

                    break;

            }
            return true;
        }

        public void OnScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY)
        {
            var scrollView = v as ScrollView;
            mScrollDistance = scrollView.ScrollY;
        }
</code>```

You could modify the logic as you want if I misunderstand your requirement .

Title: Android Drag and DRop Auto Scroll

Body:
I'm trying to figure out how to auto scroll a scrollview when a user drags an item to the edge of the screen. I'm really not getting the behavious I expect out of this code. Does anyone have an example or a technique that works?

I have this in my:

onDrag(View v, DragEvent e)
{
   case DragAction.Location:

    var currentPosition = (int)e.GetX();

    var point = GetTouchPositionFromDragEvent(v, e);

    System.Diagnostics.Debug.WriteLine($"DragAction.Location from {v.GetType()} => {currentPosition}");
    System.Diagnostics.Debug.WriteLine($"DragAction.GLOBAL   from {v.GetType()} => {point.X}");

    if (point.X > App.AppScreenWidth - 50)
    {
        _hostScrollView.ScrollToAsync(_hostScrollView.ScrollX + 30, 0, true);
    }

    if (point.X < 50)
    {
        _hostScrollView.ScrollToAsync(_hostScrollView.ScrollX - 30, 0, true);
    }
}

public static Point GetTouchPositionFromDragEvent(View item, DragEvent e)
{
    Rect rItem = new Rect();
    item.GetGlobalVisibleRect(rItem);
    return new Point(rItem.Left + (int)Math.Round(e.GetX()), rItem.Top + (int)Math.Round(e.GetY()));
}

This also has the knock on effect of only scrolling in one direction strangely and also requires the user to keep moving the item in order to fire the events which leads me to think this is entirely the wrong place to be even trying to do this scrolling.

Any pointers or nudges in the right direction would be really appreciated.

Body:
In your Activity

public class MainActivity : AppCompatActivity, View.IOnDragListener,View.IOnScrollChangeListener

private int mScrollDistance;

 ScrollView _hostScrollView= FindViewById<ScrollView>(Resource.Id.xxx);
_hostScrollView.SetOnScrollChangeListener(this);

public bool OnDrag(View v, DragEvent e)
        {
            var action = e.Action;

            var scrollView = v as ScrollView;

            switch (action)
            {
                case DragAction.Started:

                    break;
                case DragAction.Location:

                        int y = Java.Lang.Math.Round(e.GetY());
                        int translatedY = y - mScrollDistance;
                        int threshold = 50;
                        // make a scrolling up due the y has passed the threshold
                        if (translatedY < threshold)
                        {
                            // make a scroll up by 30 px
                            scrollView.ScrollBy(0, -30);
                        }
                        // make a autoscrolling down due y has passed the 500 px border
                        if (translatedY + threshold > 500)
                        {
                            // make a scroll down by 30 px
                            scrollView.ScrollBy(0, 30);
                        }

                    break;

            }
            return true;
        }

        public void OnScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY)
        {
            var scrollView = v as ScrollView;
            mScrollDistance = scrollView.ScrollY;
        }

You could modify the logic as you want if I misunderstand your requirement .


问:
How to rotate TextView on SeekBar?
I want to rotate text view on seek bar. I set thumb in center when activity is open.

If thumb is center text view show flat but if thumb slide to left then text view rotate left and if thumb slide right then text view rotate right.

答:
You can use the following code in OnSeekChangeListener </p>

```<code>if(progress<=50){
  textView.setRotation((-90*(50-progress))/50);
}else{
 textView.setRotation((90*(progress-50))/50);
}
</code>```

Title: How to rotate TextView on SeekBar?

Body:
You can use the following code in OnSeekChangeListener

if(progress<=50){
  textView.setRotation((-90*(50-progress))/50);
}else{
 textView.setRotation((90*(progress-50))/50);
}


问:
Whats the point of DOCTYPE?
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks </p>

<p>UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01? </p>

答:
The DOCTYPE declaration is required to be compliant to SGML, the language HTML is an instance of.

The DOCTYPE declaration is used by some browsers to trigger different rendering modes.

Title: Whats the point of DOCTYPE?

Body:
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks

UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01?


问:
How can I correctly print the elements to the file?

When the program comes to the yazici function, I can't print the elements of urun correctly to the file.

I can print satin_alim_kg,toplam_ucret and barkodsorgu.
    I tried making structures globally, but I couldn't.

```<code>/*
** So overwhelming. Make your code attractive and much more readable. No one will get his hands in it. Use proper spacing in between statements in your program.
** Missed closing brace at the end after return 0; statement.
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

// Structure templates
struct urun_bilgileri{
    int barkod;
    char urun_adi[50];
    char kategori[50];
    float kilogram_fiyati;
};

struct fatura_bilgileri{
    char* satin_alim_tarihi;
    float alinan_kg_miktari;
    float odenen_ucret;
};

// Global Variables
struct fatura_bilgileri *fatura;
struct urun_bilgileri *urun;
int i, barkodsorgu, faturasayac = 0;
char alinan_urun, alinan_urun_kategorisi;
float satin_alim_kg, toplam_ucret;

// Function Declarations & Definitions
void tarayici(){

    int c;
    FILE *fpbarkod = fopen("barkod.txt", "r");

    if (fpbarkod)
    {
        while ((c = getc(fpbarkod)) != EOF)
            putchar(c);
        rewind(fpbarkod);
        fclose(fpbarkod);
    }
}

void yazici(){

    FILE *fpfatura;
    time_t t;

    // Why are you allocating memory twice to fatura and urun, you haven't freed it yet in the main()?

    time(&t);
    (fatura+faturasayac)->satin_alim_tarihi = ctime(&t);

    if( (fpfatura = fopen("fatura.txt", "w+") ) == NULL)
    {
        perror("fatura.txt");
        exit(3);
    }

    fprintf(fpfatura, "Islem tarihi:%sAlinan urun:%s Barkod Numarasi:%d Urunun kategorisi:%s Alinan miktar:%.3fKG Odenen ucret:%.2f\n\n", (fatura+faturasayac)->satin_alim_tarihi, (urun+i)->urun_adi,barkodsorgu, (urun+i)->kategori, satin_alim_kg, toplam_ucret);
    printf("%f", toplam_ucret);
    fclose(fpfatura);
    faturasayac++;
}

// main()
int main()
{
    FILE *fpbarkod;
    int urun_sayac = 0, ana_menu_secim;

    if( ( fatura = (struct fatura_bilgileri *)malloc( sizeof(struct fatura_bilgileri) ) ) == NULL) // Why are you redeclaring struct fatura_bilgileri *fatura
    {
        printf("Memory Unavailable.\n"); // Check for the errors while allocating memory.
        exit(4);
    }
    if( ( urun = (struct urun_bilgileri*)malloc( sizeof(struct urun_bilgileri) ) ) == NULL) // Why are you redeclaring struct urun_bilgileri *urun
    {
        printf("Memory Unavailable.\n"); // Check for the errors while allocating memory.
        exit(5);
    }

    printf("MARKET OTOMATIK ODEME SISTEMI\n");
    baslangic:
        printf("------------------\n");
        printf("1-URUN EKLE\n");
        printf("2-URUN KATALOGU\n");
        printf("3-CIKIS\n");
        printf("------------------\n");
        printf("Lutfen islem yapmak istediginiz secenegi seciniz:");
        scanf("%d", &ana_menu_secim);
        switch(ana_menu_secim){
            case 1:
                printf("\nLutfen urunun adini giriniz:");
                scanf("%s", (urun+urun_sayac)->urun_adi);
                printf("\nLutfen urunun kategorisini giriniz:");
                scanf("%s", (urun+urun_sayac)->kategori);
                printf("\nLutfen urunun kilogram fiyatini giriniz(TL):");
                scanf("%f", &(urun+urun_sayac)->kilogram_fiyati);
                srand(time(NULL));
                (urun+urun_sayac)->barkod = rand() % (1000 + 1 - 100) + 100;
                sleep(1);
                printf("\n\nUrun Adi:%s\nUrun kategorisi:%s\nUrun Kilogram fiyati:%.2f TL\nUrun barkod numarasi:%d\n",(urun+urun_sayac)->urun_adi,(urun+urun_sayac)->kategori,(urun+urun_sayac)->kilogram_fiyati,(urun+urun_sayac)->barkod);
                if( (fpbarkod = fopen("barkod.txt","a+") ) == NULL)
                {
                    perror("barkod.txt");
                    exit(6);
                }
                fprintf(fpbarkod, "Urun Adi:%s Kategori:%s Fiyati(kg):%.2f TL Barkod No:%d\n", (urun+urun_sayac)->urun_adi, (urun+urun_sayac)->kategori, (urun+urun_sayac)->kilogram_fiyati, (urun+urun_sayac)->barkod);
                rewind(fpbarkod);
                fclose(fpbarkod);
                sleep(1);
                printf("\n\nUrun ekleme basarili\n\n");
                urun_sayac++;
                goto baslangic; // Avoid use of goto as far as possible. It makes your program unreadable, ambiguous and unstructured.
            case 2:
                printf("-------------------KATALOG-------------------\n");
                tarayici();
                printf("---------------------------------------------\n");
                geribarkodsorgu:
                    printf("\nLutfen satin almak istediginiz urunun barkod numarasini giriniz:");
                    scanf("%d" , &barkodsorgu);
                    sleep(1);
                    for(i = 0; i <= urun_sayac; i++){
                        if(barkodsorgu == (urun+i)->barkod){
                            printf("\n%s kilogram Fiyati:%.2f\n", (urun+i)->urun_adi, (urun+i)->kilogram_fiyati);
                            goto satinalimkg;
                        }
                        else if(i == urun_sayac){
                            printf("\n\nYANLIS BARKOD NUMARASI\n");
                            goto geribarkodsorgu;
                        }
                        else
                            continue;
                    }
                satinalimkg:
                    sleep(1);
                    printf("\nLutfen satin almak istediginiz miktari giriniz(kg):");
                    scanf("%f" , &satin_alim_kg);
                    if(satin_alim_kg <= 0){
                        printf("\n\nLutfen satin almak istediginiz miktari dogru giriniz\n");
                        goto satinalimkg;
                    }
                toplam_ucret = (satin_alim_kg) * ((urun+i)->kilogram_fiyati);
                printf("Toplam ucret:%.2f", toplam_ucret);
                yazici();
                break;
            case 3:
                return 0;
            default:
                printf("\nLutfen menudeki seceneklerden birini seciniz.\n\n");
                sleep(1);
                goto baslangic;
                break;
        }
    // If you are done with fatura and urun free them.
    free(fatura);
    free(urun);
    return 0;
}

</code>```

How can I correctly print the elements to the file?
  Should I redefine structures in the printer function

答:
if you need to insert something into the file you need to define a char* values variable and populate it with some content.

```<code>fd = open("barkod.txt",O_CREAT|O_RDWR,0666);
    file = fdopen(fd,"r+");
    ret = fprintf(file,"%s ",values);
    if(ret == -1 ) {
    fprintf(stderr,"Error in fprintf");
    exit(-1)}
    fflush(file);
</code>```

Instead if you need to read some information from the file you can use the following function:

```<code>#define SIZE 4096

char * malloc_buff(int dim){
    char *buf;
    buf=malloc(sizeof(char)*dim);
    if(buf==NULL){
        perror("Errore in malloc");
    }
    return buf;
}

char * lecture_file(){
    FILE* fd;
    char* disponibili;
    disponibili=malloc_buff(SIZE);
    errno=0;
    fd=fopen("bardok.txt","r+");
    if(errno!=0){
        fprintf(stderr,"error in open file\n");
        exit(-1);
    }
    fread(disponibili,sizeof(char),SIZE,fd);
    if(fclose(fd)){
        fprintf(stderr,"error in close\n");
        exit(-1);
    }
    return disponibili;
}
</code>```

Body:
When the program comes to the yazici function, I can't print the elements of urun correctly to the file.

I can print satin_alim_kg,toplam_ucret and barkodsorgu.
    I tried making structures globally, but I couldn't.

/*
** So overwhelming. Make your code attractive and much more readable. No one will get his hands in it. Use proper spacing in between statements in your program.
** Missed closing brace at the end after return 0; statement.
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

// Structure templates
struct urun_bilgileri{
    int barkod;
    char urun_adi[50];
    char kategori[50];
    float kilogram_fiyati;
};

struct fatura_bilgileri{
    char* satin_alim_tarihi;
    float alinan_kg_miktari;
    float odenen_ucret;
};

// Global Variables
struct fatura_bilgileri *fatura;
struct urun_bilgileri *urun;
int i, barkodsorgu, faturasayac = 0;
char alinan_urun, alinan_urun_kategorisi;
float satin_alim_kg, toplam_ucret;

// Function Declarations & Definitions
void tarayici(){

    int c;
    FILE *fpbarkod = fopen("barkod.txt", "r");

    if (fpbarkod)
    {
        while ((c = getc(fpbarkod)) != EOF)
            putchar(c);
        rewind(fpbarkod);
        fclose(fpbarkod);
    }
}

void yazici(){

    FILE *fpfatura;
    time_t t;

    // Why are you allocating memory twice to fatura and urun, you haven't freed it yet in the main()?

    time(&t);
    (fatura+faturasayac)->satin_alim_tarihi = ctime(&t);

    if( (fpfatura = fopen("fatura.txt", "w+") ) == NULL)
    {
        perror("fatura.txt");
        exit(3);
    }

    fprintf(fpfatura, "Islem tarihi:%sAlinan urun:%s Barkod Numarasi:%d Urunun kategorisi:%s Alinan miktar:%.3fKG Odenen ucret:%.2f\n\n", (fatura+faturasayac)->satin_alim_tarihi, (urun+i)->urun_adi,barkodsorgu, (urun+i)->kategori, satin_alim_kg, toplam_ucret);
    printf("%f", toplam_ucret);
    fclose(fpfatura);
    faturasayac++;
}

// main()
int main()
{
    FILE *fpbarkod;
    int urun_sayac = 0, ana_menu_secim;

    if( ( fatura = (struct fatura_bilgileri *)malloc( sizeof(struct fatura_bilgileri) ) ) == NULL) // Why are you redeclaring struct fatura_bilgileri *fatura
    {
        printf("Memory Unavailable.\n"); // Check for the errors while allocating memory.
        exit(4);
    }
    if( ( urun = (struct urun_bilgileri*)malloc( sizeof(struct urun_bilgileri) ) ) == NULL) // Why are you redeclaring struct urun_bilgileri *urun
    {
        printf("Memory Unavailable.\n"); // Check for the errors while allocating memory.
        exit(5);
    }

    printf("MARKET OTOMATIK ODEME SISTEMI\n");
    baslangic:
        printf("------------------\n");
        printf("1-URUN EKLE\n");
        printf("2-URUN KATALOGU\n");
        printf("3-CIKIS\n");
        printf("------------------\n");
        printf("Lutfen islem yapmak istediginiz secenegi seciniz:");
        scanf("%d", &ana_menu_secim);
        switch(ana_menu_secim){
            case 1:
                printf("\nLutfen urunun adini giriniz:");
                scanf("%s", (urun+urun_sayac)->urun_adi);
                printf("\nLutfen urunun kategorisini giriniz:");
                scanf("%s", (urun+urun_sayac)->kategori);
                printf("\nLutfen urunun kilogram fiyatini giriniz(TL):");
                scanf("%f", &(urun+urun_sayac)->kilogram_fiyati);
                srand(time(NULL));
                (urun+urun_sayac)->barkod = rand() % (1000 + 1 - 100) + 100;
                sleep(1);
                printf("\n\nUrun Adi:%s\nUrun kategorisi:%s\nUrun Kilogram fiyati:%.2f TL\nUrun barkod numarasi:%d\n",(urun+urun_sayac)->urun_adi,(urun+urun_sayac)->kategori,(urun+urun_sayac)->kilogram_fiyati,(urun+urun_sayac)->barkod);
                if( (fpbarkod = fopen("barkod.txt","a+") ) == NULL)
                {
                    perror("barkod.txt");
                    exit(6);
                }
                fprintf(fpbarkod, "Urun Adi:%s Kategori:%s Fiyati(kg):%.2f TL Barkod No:%d\n", (urun+urun_sayac)->urun_adi, (urun+urun_sayac)->kategori, (urun+urun_sayac)->kilogram_fiyati, (urun+urun_sayac)->barkod);
                rewind(fpbarkod);
                fclose(fpbarkod);
                sleep(1);
                printf("\n\nUrun ekleme basarili\n\n");
                urun_sayac++;
                goto baslangic; // Avoid use of goto as far as possible. It makes your program unreadable, ambiguous and unstructured.
            case 2:
                printf("-------------------KATALOG-------------------\n");
                tarayici();
                printf("---------------------------------------------\n");
                geribarkodsorgu:
                    printf("\nLutfen satin almak istediginiz urunun barkod numarasini giriniz:");
                    scanf("%d" , &barkodsorgu);
                    sleep(1);
                    for(i = 0; i <= urun_sayac; i++){
                        if(barkodsorgu == (urun+i)->barkod){
                            printf("\n%s kilogram Fiyati:%.2f\n", (urun+i)->urun_adi, (urun+i)->kilogram_fiyati);
                            goto satinalimkg;
                        }
                        else if(i == urun_sayac){
                            printf("\n\nYANLIS BARKOD NUMARASI\n");
                            goto geribarkodsorgu;
                        }
                        else
                            continue;
                    }
                satinalimkg:
                    sleep(1);
                    printf("\nLutfen satin almak istediginiz miktari giriniz(kg):");
                    scanf("%f" , &satin_alim_kg);
                    if(satin_alim_kg <= 0){
                        printf("\n\nLutfen satin almak istediginiz miktari dogru giriniz\n");
                        goto satinalimkg;
                    }
                toplam_ucret = (satin_alim_kg) * ((urun+i)->kilogram_fiyati);
                printf("Toplam ucret:%.2f", toplam_ucret);
                yazici();
                break;
            case 3:
                return 0;
            default:
                printf("\nLutfen menudeki seceneklerden birini seciniz.\n\n");
                sleep(1);
                goto baslangic;
                break;
        }
    // If you are done with fatura and urun free them.
    free(fatura);
    free(urun);
    return 0;
}

How can I correctly print the elements to the file?
  Should I redefine structures in the printer function

Body:
if you need to insert something into the file you need to define a char* values variable and populate it with some content.

fd = open("barkod.txt",O_CREAT|O_RDWR,0666);
    file = fdopen(fd,"r+");
    ret = fprintf(file,"%s ",values);
    if(ret == -1 ) {
    fprintf(stderr,"Error in fprintf");
    exit(-1)}
    fflush(file);

Instead if you need to read some information from the file you can use the following function:

#define SIZE 4096

char * malloc_buff(int dim){
    char *buf;
    buf=malloc(sizeof(char)*dim);
    if(buf==NULL){
        perror("Errore in malloc");
    }
    return buf;
}

char * lecture_file(){
    FILE* fd;
    char* disponibili;
    disponibili=malloc_buff(SIZE);
    errno=0;
    fd=fopen("bardok.txt","r+");
    if(errno!=0){
        fprintf(stderr,"error in open file\n");
        exit(-1);
    }
    fread(disponibili,sizeof(char),SIZE,fd);
    if(fclose(fd)){
        fprintf(stderr,"error in close\n");
        exit(-1);
    }
    return disponibili;
}


问:
golang snippets/auto completion not working with vs code
I use VS Code with wsl terminal. I have installed many extensions for theme and snippet. For C/C++, Python, JS,HTML/CSS, etc snippets work but with GO it's not working. When I type imp and I expect to get auto-completion like import, but it does not show up. It works with sublime though. For GO, I have installed

Go (from Microsoft)

Golang postfix code completion

gotemplate-syntax

GO snippets

Especially GO snippets is designed to give snippet for func main but it won't do so.
Anything I am missing on?

答:
One thing you can do is enable the use of Go's Language Server - gopls. Go to the Settings and search for "Use Language Server". You will need to reload (or restart) your VSCode. On reload it should warn you that you need to install/update gopls and other tools - do it and you should be fine.

Note:

gopls is beta at best. It will sometimes crash, use excessive CPU and so on. It's not ideal but people are working on it and it's getting better every day. Just keep in mind that it might be less that ideal, OK? :)


问:
React FC with forwardedRef
Im facing issue with ref - I need to ref to function component and pass props to it. So far I got my Parent component and Child Component. In my parent component I need to use ref to my child. I need to work with projectSectionItem inside my parent component.

Parent:

```<code>const projectSectionItem = useRef<HTMLDivElement>(null);

        return i.showOnHP === 1 ?
            <Project key={index}
                url={`${URL}${i.button_image.image}`}
                client={i.client_name}
                project={i.project.en}
                btn_color={"#000"}
                btn_text={i.button_text}
                href={`/cases/${i.slug}`}
                ref={projectSectionItem}
            >
                {index === 0 ?
                    <ScrollList>
                        {data.map((i, index) => { return <ScrollListItem data-index={index} key={index} ref={projectIndicator} onClick={(e: React.MouseEvent<HTMLLIElement>) => scrollToNextProject(e)} /> })}
                    </ScrollList>
                    : null}
            </Project>
                : null;
        })}
</code>```

Child:

```<code>type APIProps = {
    url?: string,
    client?: string,
    project?: string,
    btn_text?: string,
    btn_color?: string,
    href?: string,
}

type HWWProps = {
    order_client?: number,
    order_project?: number,
    className?: string
    ref?: React.MutableRefObject<HTMLDivElement>
}

type ProjectProps = APIProps & HWWProps;

export const Project: React.FC<ProjectProps> = props => {
    return (
        <StyledProject className={props.className}>
            <ProjectContainer>
                <ProjectImage src={props.url} alt={props.client} />
                <ProjectTextWrapper>
                    <ProjectBrand order_client={props.order_client}>{props.client}</ProjectBrand>
                    <ProjectName order_project={props.order_project}>{props.project}</ProjectName>
                    <ButtonExtend as={Button} color={props.btn_color}><Link to={props.href}>{props.btn_text}</Link></ButtonExtend>
                </ProjectTextWrapper>
            </ProjectContainer>
            {props.children}
        </StyledProject>
    )
}
</code>```

答:
You cannot add refs to functional component without using React.forwardRef to either pass it on to a HTMLDIVElement or using useImperativeHandle hook to expose some functions

Since you wish to add the ref a DOM element in Project component you can pass the ref on to the StyledProject component which is a styled component by using innerRef prop

```<code>export const Project: React.FC<ProjectProps> = React.forwardRef((props ,ref: : Ref<HTMLDivElement>)=> {
    return (
        <StyledProject className={props.className} innerRef={ref}>
            <ProjectContainer>
                <ProjectImage src={props.url} alt={props.client} />
                <ProjectTextWrapper>
                    <ProjectBrand order_client={props.order_client}>{props.client}</ProjectBrand>
                    <ProjectName order_project={props.order_project}>{props.project}</ProjectName>
                    <ButtonExtend as={Button} color={props.btn_color}><Link to={props.href}>{props.btn_text}</Link></ButtonExtend>
                </ProjectTextWrapper>
            </ProjectContainer>
            {props.children}
        </StyledProject>
    )
});
</code>```

After doing this, you can access the ref in parent like projectSectionItem.current

Title: React FC with forwardedRef

Body:
Im facing issue with ref - I need to ref to function component and pass props to it. So far I got my Parent component and Child Component. In my parent component I need to use ref to my child. I need to work with projectSectionItem inside my parent component.

Parent:

const projectSectionItem = useRef<HTMLDivElement>(null);

        return i.showOnHP === 1 ?
            <Project key={index}
                url={`${URL}${i.button_image.image}`}
                client={i.client_name}
                project={i.project.en}
                btn_color={"#000"}
                btn_text={i.button_text}
                href={`/cases/${i.slug}`}
                ref={projectSectionItem}
            >
                {index === 0 ?
                    <ScrollList>
                        {data.map((i, index) => { return <ScrollListItem data-index={index} key={index} ref={projectIndicator} onClick={(e: React.MouseEvent<HTMLLIElement>) => scrollToNextProject(e)} /> })}
                    </ScrollList>
                    : null}
            </Project>
                : null;
        })}

Child:

type APIProps = {
    url?: string,
    client?: string,
    project?: string,
    btn_text?: string,
    btn_color?: string,
    href?: string,
}

type HWWProps = {
    order_client?: number,
    order_project?: number,
    className?: string
    ref?: React.MutableRefObject<HTMLDivElement>
}

type ProjectProps = APIProps & HWWProps;

export const Project: React.FC<ProjectProps> = props => {
    return (

    )
}

Body:
You cannot add refs to functional component without using React.forwardRef to either pass it on to a HTMLDIVElement or using useImperativeHandle hook to expose some functions

Since you wish to add the ref a DOM element in Project component you can pass the ref on to the StyledProject component which is a styled component by using innerRef prop

export const Project: React.FC<ProjectProps> = React.forwardRef((props ,ref: : Ref<HTMLDivElement>)=> {
    return (
        <StyledProject className={props.className} innerRef={ref}>
            <ProjectContainer>
                <ProjectImage src={props.url} alt={props.client} />
                <ProjectTextWrapper>
                    <ProjectBrand order_client={props.order_client}>{props.client}</ProjectBrand>
                    <ProjectName order_project={props.order_project}>{props.project}</ProjectName>
                    <ButtonExtend as={Button} color={props.btn_color}><Link to={props.href}>{props.btn_text}</Link></ButtonExtend>
                </ProjectTextWrapper>
            </ProjectContainer>
            {props.children}
        </StyledProject>
    )
});

After doing this, you can access the ref in parent like projectSectionItem.current


问:
System.NullReferenceException: Object reference not set to an instance of an object

Possible Duplicate:

  System.NullReferenceException: Object reference not set to an instance of an object

look at my code

```<code>if (ViewState["Edit"].ToString() == "new") {
}
else {
      row = _section.GetBannerEntry(ViewState["Edit"].ToString());
}
</code>```

I was getting the error on this line if (ViewState["Edit"].ToString() == "new") I replaced with if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") it works.

Now I am getting the same error here in else row = _section.GetBannerEntry(ViewState["Edit"].ToString());

please help

答:
If ViewState["Edit"] hasn't been set, .ToString() will throw an exception.

Try one of these:

if (ViewState["Edit"]!= null && ViewState["Edit"].ToString() == "new") //best one

if (ViewState["Edit"] + "" == "new")

Body:
Possible Duplicate:

  System.NullReferenceException: Object reference not set to an instance of an object

look at my code

if (ViewState["Edit"].ToString() == "new") {
}
else {
      row = _section.GetBannerEntry(ViewState["Edit"].ToString());
}

I was getting the error on this line if (ViewState["Edit"].ToString() == "new") I replaced with if (ViewState["Edit"] != null && ViewState["Edit"].ToString() == "new") it works.

Now I am getting the same error here in else row = _section.GetBannerEntry(ViewState["Edit"].ToString());

please help


问:
SigninScreen.js and functions.js - how to make function.js function update useState in SigninScreen.js?
I have two files: one for functions (functions.js) and one for SigninScreen, please see the code below. How can I make the signInUser formula refer back to the SigninScreen (and e.g. update useState value of email/password there)?

Right now, it seems as if the signInUser function does not have access to that scope because I get error message stating 'setEmail is not a function'.

functions.js

```<code>export async function signInUser(email, password) {
  console.log('Attempting to sign in');

  credentials = {
  email: email.toString(),
  password: password.toString()
  }

  const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials)
  };
  const response = await fetch('http://localhost:3000/signin', requestOptions)
  const data = await response.json()

  setEmail('xaxaxaxa')

  console.log(data)

}
</code>```

SigninScreen.js

```<code>import React, { useState, useContext } from 'react'
import { View, StyleSheet, Button } from 'react-native'
import { Text, Input } from 'react-native-elements'
import Spacer from '../components/Spacer'
import { signInUser } from '../functions/functions.js'
import UserContext from '../context/appContext.js'

const SigninScreen = ({ navigation }) => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  // This can be removed later
  const user = useContext(UserContext);
  console.log(user);

  return (
  <UserContext.Consumer>
  {({userloggerinfo, updateUserLoggerInfo}) => (
  <View style={styles.container}>
    <Spacer>
      <Text h3>Sign in</Text>
    </Spacer>
    <Input
    label="Email"
    value={email}
    onChangeText={setEmail}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer />
    <Input
    secureTextEntry
    label="Password"
    value={password}
    onChangeText={setPassword}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer>
      <Button
      title="Sign in"
      onPress={() => { signInUser(email, password); console.log('hejjjjjj'); }}
      />
    </Spacer>
  </View>
  )}
  </UserContext.Consumer>
  )
}

SigninScreen.navigationOptions = () => {
  return {
    header: null
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    marginBottom: 250
  }
})

export default SigninScreen
</code>```

Kind regards

答: Utilizing the return statement did the trick</p>

Body:
I have two files: one for functions (functions.js) and one for SigninScreen, please see the code below. How can I make the signInUser formula refer back to the SigninScreen (and e.g. update useState value of email/password there)?

Right now, it seems as if the signInUser function does not have access to that scope because I get error message stating 'setEmail is not a function'.

functions.js

export async function signInUser(email, password) {
  console.log('Attempting to sign in');

  credentials = {
  email: email.toString(),
  password: password.toString()
  }

  const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials)
  };
  const response = await fetch('http://localhost:3000/signin', requestOptions)
  const data = await response.json()

  setEmail('xaxaxaxa')

  console.log(data)

}

SigninScreen.js

import React, { useState, useContext } from 'react'
import { View, StyleSheet, Button } from 'react-native'
import { Text, Input } from 'react-native-elements'
import Spacer from '../components/Spacer'
import { signInUser } from '../functions/functions.js'
import UserContext from '../context/appContext.js'

const SigninScreen = ({ navigation }) => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  // This can be removed later
  const user = useContext(UserContext);
  console.log(user);

  return (
  <UserContext.Consumer>
  {({userloggerinfo, updateUserLoggerInfo}) => (
  <View style={styles.container}>
    <Spacer>
      <Text h3>Sign in</Text>
    </Spacer>
    <Input
    label="Email"
    value={email}
    onChangeText={setEmail}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer />
    <Input
    secureTextEntry
    label="Password"
    value={password}
    onChangeText={setPassword}
    autoCapitalize="none"
    autoCorrect={false}
    />
    <Spacer>
      <Button
      title="Sign in"
      onPress={() => { signInUser(email, password); console.log('hejjjjjj'); }}
      />
    </Spacer>
  </View>
  )}
  </UserContext.Consumer>
  )
}

SigninScreen.navigationOptions = () => {
  return {
    header: null
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    marginBottom: 250
  }
})

export default SigninScreen

Kind regards


问:
Time delay in For loop in c#
how can i use a time delay in a loop after certain rotation?
Suppose:

```<code>for(int i = 0 ; i<64;i++)
{
........
}
</code>```

i want 1 sec delay after each 8 rotation.

答:
Once I needed to write a program witch was so sensitive and needed accurate timing (about Nano seconds).

I used all sorts of stuff like Thread.Sleep(), Timer and... but none of them was that accurate that could answer my needs so I used this code for delaying:

```<code>var stopWatch = new Stopwatch();
for(int i = 0 ; i<64;i++)
{
stopWatch.Restart();
while (stopWatch.ElapsedMilliseconds <= 1000)
{

}
}
</code>```

Of course this way is not very CPU friendly, yet when you need accuracy that much you have to go old school.

Title: Time delay in For loop in c#

Body:
how can i use a time delay in a loop after certain rotation?
Suppose:

for(int i = 0 ; i<64;i++)
{
........
}

i want 1 sec delay after each 8 rotation.

Body:
Once I needed to write a program witch was so sensitive and needed accurate timing (about Nano seconds).

I used all sorts of stuff like Thread.Sleep(), Timer and... but none of them was that accurate that could answer my needs so I used this code for delaying:

var stopWatch = new Stopwatch();
for(int i = 0 ; i<64;i++)
{
stopWatch.Restart();
while (stopWatch.ElapsedMilliseconds <= 1000)
{

}
}

Of course this way is not very CPU friendly, yet when you need accuracy that much you have to go old school.


问:
integrating TM4J (Test management for Jira) Adpavist with Karate Tests
Does Karate API tests supports integration with TM4J (Test management for Jira - Adaptavist)?
We have been using Karate for our GraphQL layer and it has been quite successful so far. we have a requirement to integrate TM4J across multiple frameworks across the company and hence wanted to know if it is possible?

TM4J supports cucumber.options

Any help on this is much appreciated.

Thanks!

答:
Since Karate exports the cucumber-json, this may work without any change.

Also refer this thread: https://github.com/intuit/karate/issues/619

And note that Karate does one thing slightly differently, so you may need to be aware of that: https://stackoverflow.com/a/56516016/143475

Anything beyond this we consider the responsibility of the external tool side, or you have to write a custom-hook: https://stackoverflow.com/a/59080128/143475


问:
How to query employee details and relate their performance metrics?
I am fetching the id, first name, and last name of all employees that are approved and not archived.  Then I am looping these results and using the ids to query other tables to collect some count data.

I tried the below code, but I am not getting the expected output.

```<code>$queryEmp = "
    SELECT id, firstname, lastname
    FROM tbl_employee as e
    WHERE is_archive=0 and is_approved=1
";
$getQuery= $this->db->query($queryEmp);
$result= $getQuery->result();
foreach ($result as $key=> $value) {
    //echo "```";
    print_r($value);

    $day = "MONTH(date_of_created) = DATE(CURRENT_DATE())";
    $group = "f_id IN (SELECT MAX(f_id) FROM tbl_fileStatus GROUP BY f_bankid)";
    $condiion = "and ba.createdby='" . $value->id . "' and " . $day ." and " . $group;
    $query2 = "
        select
            (SELECT COUNT(c_id)
             FROM tbl_lead
             WHERE leadstatus='1' AND ".$day.") as confirmCount,

            (SELECT COUNT(f_id)
             FROM tbl_fileStatus as fs
             join tbl_bankdata as ba on ba.bank_id=fs.f_bankid
             WHERE fs.f_filestatus=1 " . $condiion . ") as disbursed,

            (SELECT COUNT(f_id)
             FROM tbl_fileStatus as fs
             join tbl_bankdata as ba on ba.bank_id=fs.f_bankid
             WHERE fs.f_filestatus=2 ".$condiion.") as filesubmit
    ";
    # code...
    $getQuery2= $this->db->query($query2);
    $result2[]=$getQuery2->result();
}
echo "```";
print_r(result2);
</code>```

$result looks like this:

```<code>Array (
    [0] => stdClass Object (
        [id] => 1
        [firstname] => xyz
        [lastname] => xyz
    )
    ...
)
</code>```

Second query output:

```<code>Array (
    [0] => Array (
        [0] => stdClass Object (
            [fallowCall] => 0
            [confirmCount] => 0
            [disbursed] => 0
            [filesubmit] => 0
        )
    )
    ...
)
</code>```

How can I produce the correct results which relate respective employees with with their performance metrics?  Either this structure:

```<code>Array (
    [0] => stdClass Object (
        [id] => 1
        [firstname] => xyz
        [lastname] => xyz
        [somename] => (
            [fallowCall] => 0
            [confirmCount] => 0
            [disbursed] => 0
            [filesubmit] => 0
        )
    )
    ...
)
</code>```

Or this structure:

```<code>Array (
    [0] => stdClass Object (
        [id] => 1
        [firstname] => xyz
        [lastname] => xyz
        [fallowCall] => 0
        [confirmCount] => 0
        [disbursed] => 0
        [filesubmit] => 0
    )
    ...
)
</code>```

I have added the my table structure and some sample data here: https://www.db-fiddle.com/f/8MoWmKPuzTrrC3DQJsiX35/0

some notes here

1) createdby is the id of table tbl_employee

2) lead_id in the bank table is the c_id of the table tbl_lead

3) f_bankid in the tbl_fileStatus is the bank_id of the table tbl_bankdata

答:
There is actually no  need to create the additional depth/complexity just to hold the count data.  Furthermore, by using a combination of LEFT JOINs to connect the related tables and apply your required conditional rules, you can achieve your desired result by making just one trip to the database.  This will without question provide superior efficiency for your application.  LEFT JOINs are important to use so that counts can be zero without excluding employees from the result set.

Also, I should point out that your attempted query was mistakenly comparing a MONTH() value against a DATE() value -- that was never going to end well. :)  In fact, to ensure that your sql is accurately isolating the current month from the current year, you need to be also checking the YEAR value.

My recommended sql:

```<code>SELECT
    employees.id,
    employees.firstname,
    employees.lastname,
    COUNT(DISTINCT leads.c_id) AS leadsThisMonth,
    SUM(IF(fileStatus.f_filestatus = 1, 1, 0)) AS disbursedThisMonth,
    SUM(IF(fileStatus.f_filestatus = 2, 1, 0)) AS filesubmitThisMonth
FROM tbl_employee AS employees

LEFT JOIN tbl_lead AS leads
    ON employees.id = leads.createdby
        AND leadstatus = 1
        AND MONTH(leads.date_of_created) = MONTH(CURRENT_DATE())
        AND YEAR(leads.date_of_created) = YEAR(CURRENT_DATE())

LEFT JOIN tbl_bankdata AS bankData
    ON employees.id = bankData.createdby

LEFT JOIN tbl_fileStatus AS fileStatus
    ON bankData.bank_id = fileStatus.f_bankid
        AND MONTH(fileStatus.date_of_created) = MONTH(CURRENT_DATE())
        AND YEAR(fileStatus.date_of_created) = YEAR(CURRENT_DATE())
        AND fileStatus.f_id = (
                SELECT MAX(subFileStatus.f_id)
                FROM tbl_fileStatus AS subFileStatus
                WHERE subFileStatus.f_bankid = bankData.bank_id
                GROUP BY subFileStatus.f_bankid
            )

WHERE employees.is_archive = 0
    AND employees.is_approved = 1

GROUP BY employees.id, employees.firstname, employees.lastname
</code>```

The SUM(IF()) expression is a technique used to execute a "conditional count".  "Aggregate data" is formed by using GROUP BY and there are specialized "aggregate functions" which must be used to create linear/flat data from these clusters/non-flat collections of data.  fileStatus data is effectively piled up upon itself due to the GROUP BY call.  If COUNT(fileStatus.f_filestatus) was called, it would count all of the rows in the cluster.  Since you wish to differentiate between f_filestatus = 1 and f_filestatus = 2, an IF() statement is used.  This is doing the same thing as COUNT() (adding 1 for every qualifying occurrence), but it is different from COUNT() in that it does not count specific rows (within the scope of the cluster) unless the IF() expression is satisfied.  Another example.

Here is a db fiddle demo with some adjustments to your supplied sample data: https://www.db-fiddle.com/f/8MoWmKPuzTrrC3DQJsiX35/4  (The result set will only be "good" while the current is June of this year.)

After saving the above string as $sql, you can simply execute it and loop through the array of objects like this:

```<code>foreach ($this->db->query($sql)->result() as $object) {
    // these are the properties available in each object
    // $object->id
    // $object->firstname
    // $object->lastname
    // $object->leadsThisMonth
    // $object->disbursedThisMonth
    // $object->filesubmitThisMonth
}
</code>```

Body:
I am fetching the id, first name, and last name of all employees that are approved and not archived.  Then I am looping these results and using the ids to query other tables to collect some count data.

I tried the below code, but I am not getting the expected output.

$queryEmp = "
    SELECT id, firstname, lastname
    FROM tbl_employee as e
    WHERE is_archive=0 and is_approved=1
";
$getQuery= $this->db->query($queryEmp);
$result= $getQuery->result();
foreach ($result as $key=> $value) {
    //echo "
";
    print_r($value);

    $day = "MONTH(date_of_created) = DATE(CURRENT_DATE())";
    $group = "f_id IN (SELECT MAX(f_id) FROM tbl_fileStatus GROUP BY f_bankid)";
    $condiion = "and ba.createdby='" . $value->id . "' and " . $day ." and " . $group;
    $query2 = "
        select
            (SELECT COUNT(c_id)
             FROM tbl_lead
             WHERE leadstatus='1' AND ".$day.") as confirmCount,

            (SELECT COUNT(f_id)
             FROM tbl_fileStatus as fs
             join tbl_bankdata as ba on ba.bank_id=fs.f_bankid
             WHERE fs.f_filestatus=1 " . $condiion . ") as disbursed,

            (SELECT COUNT(f_id)
             FROM tbl_fileStatus as fs
             join tbl_bankdata as ba on ba.bank_id=fs.f_bankid
             WHERE fs.f_filestatus=2 ".$condiion.") as filesubmit
    ";
    # code...
    $getQuery2= $this->db->query($query2);
    $result2[]=$getQuery2->result();
}
echo "
";
print_r(result2);

$result looks like this:

Array (
    [0] => stdClass Object (
        [id] => 1
        [firstname] => xyz
        [lastname] => xyz
    )
    ...
)

Second query output:

Array (
    [0] => Array (
        [0] => stdClass Object (
            [fallowCall] => 0
            [confirmCount] => 0
            [disbursed] => 0
            [filesubmit] => 0
        )
    )
    ...
)

How can I produce the correct results which relate respective employees with with their performance metrics?  Either this structure:

Array (
    [0] => stdClass Object (
        [id] => 1
        [firstname] => xyz
        [lastname] => xyz
        [somename] => (
            [fallowCall] => 0
            [confirmCount] => 0
            [disbursed] => 0
            [filesubmit] => 0
        )
    )
    ...
)

Or this structure:

Array (
    [0] => stdClass Object (
        [id] => 1
        [firstname] => xyz
        [lastname] => xyz
        [fallowCall] => 0
        [confirmCount] => 0
        [disbursed] => 0
        [filesubmit] => 0
    )
    ...
)

I have added the my table structure and some sample data here: https://www.db-fiddle.com/f/8MoWmKPuzTrrC3DQJsiX35/0

some notes here

1) createdby is the id of table tbl_employee

2) lead_id in the bank table is the c_id of the table tbl_lead

3) f_bankid in the tbl_fileStatus is the bank_id of the table tbl_bankdata

Body:
There is actually no  need to create the additional depth/complexity just to hold the count data.  Furthermore, by using a combination of LEFT JOINs to connect the related tables and apply your required conditional rules, you can achieve your desired result by making just one trip to the database.  This will without question provide superior efficiency for your application.  LEFT JOINs are important to use so that counts can be zero without excluding employees from the result set.

Also, I should point out that your attempted query was mistakenly comparing a MONTH() value against a DATE() value -- that was never going to end well. :)  In fact, to ensure that your sql is accurately isolating the current month from the current year, you need to be also checking the YEAR value.

My recommended sql:

SELECT
    employees.id,
    employees.firstname,
    employees.lastname,
    COUNT(DISTINCT leads.c_id) AS leadsThisMonth,
    SUM(IF(fileStatus.f_filestatus = 1, 1, 0)) AS disbursedThisMonth,
    SUM(IF(fileStatus.f_filestatus = 2, 1, 0)) AS filesubmitThisMonth
FROM tbl_employee AS employees

LEFT JOIN tbl_lead AS leads
    ON employees.id = leads.createdby
        AND leadstatus = 1
        AND MONTH(leads.date_of_created) = MONTH(CURRENT_DATE())
        AND YEAR(leads.date_of_created) = YEAR(CURRENT_DATE())

LEFT JOIN tbl_bankdata AS bankData
    ON employees.id = bankData.createdby

LEFT JOIN tbl_fileStatus AS fileStatus
    ON bankData.bank_id = fileStatus.f_bankid
        AND MONTH(fileStatus.date_of_created) = MONTH(CURRENT_DATE())
        AND YEAR(fileStatus.date_of_created) = YEAR(CURRENT_DATE())
        AND fileStatus.f_id = (
                SELECT MAX(subFileStatus.f_id)
                FROM tbl_fileStatus AS subFileStatus
                WHERE subFileStatus.f_bankid = bankData.bank_id
                GROUP BY subFileStatus.f_bankid
            )

WHERE employees.is_archive = 0
    AND employees.is_approved = 1

GROUP BY employees.id, employees.firstname, employees.lastname

The SUM(IF()) expression is a technique used to execute a "conditional count".  "Aggregate data" is formed by using GROUP BY and there are specialized "aggregate functions" which must be used to create linear/flat data from these clusters/non-flat collections of data.  fileStatus data is effectively piled up upon itself due to the GROUP BY call.  If COUNT(fileStatus.f_filestatus) was called, it would count all of the rows in the cluster.  Since you wish to differentiate between f_filestatus = 1 and f_filestatus = 2, an IF() statement is used.  This is doing the same thing as COUNT() (adding 1 for every qualifying occurrence), but it is different from COUNT() in that it does not count specific rows (within the scope of the cluster) unless the IF() expression is satisfied.  Another example.

Here is a db fiddle demo with some adjustments to your supplied sample data: https://www.db-fiddle.com/f/8MoWmKPuzTrrC3DQJsiX35/4  (The result set will only be "good" while the current is June of this year.)

After saving the above string as $sql, you can simply execute it and loop through the array of objects like this:

foreach ($this->db->query($sql)->result() as $object) {
    // these are the properties available in each object
    // $object->id
    // $object->firstname
    // $object->lastname
    // $object->leadsThisMonth
    // $object->disbursedThisMonth
    // $object->filesubmitThisMonth
}


问:
MLPRegressor working but results don't make any sense
I am building a neural network with my research data in two ways: with a statistical programm (SPSS) and with python.
I am using the scikit learn MLPRegressor. The problem I have is that whereas my code is , apparently, well written (because it runs), the results do not make sense. The r2score should be around 0.70 ( it is-4147.64) and the correlation represented in the graph should be almost linear. (it is just a straight line at a constant distance from X axis).  Also the x and y axis should have values ranging from 0 to 180, which is not the case ( X from 20 to 100, y from -4100 to -3500)

If any of you can give a hand I would really appreciate it.
Thank you!!!!!!

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

from sklearn import neighbors, datasets, preprocessing
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import r2_score

vhdata = pd.read_csv('vhrawdata.csv')
vhdata.head()

X = vhdata[['PA NH4', 'PH NH4', 'PA K', 'PH K', 'PA NH4 + PA K', 'PH NH4 + PH K', 'PA IS', 'PH IS']]
y = vhdata['PMI']

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import Normalizer
scaler = Normalizer().fit(X_train)
X_train_norm = scaler.transform(X_train)
X_test_norm = scaler.transform(X_test)

nnref = MLPRegressor(hidden_layer_sizes = [4], activation = 'logistic', solver = 'sgd', alpha = 1,
                     learning_rate= 'constant', learning_rate_init= 0.6, max_iter=40000, momentum=
                     0.3).fit(X_train, y_train)

y_predictions= nnref.predict(X_test)

print('Accuracy of NN classifier on training set (R2 score): {:.2f}'.format(nnref.score(X_train_norm, y_train)))
print('Accuracy of NN classifier on test set (R2 score): {:.2f}'.format(nnref.score(X_test_norm, y_test)))

plt.figure()
plt.scatter(y_test,y_predictions, marker = 'o', color='red')
plt.xlabel('PMI expected (hrs)')
plt.ylabel('PMI predicted (hrs)')
plt.title('Correlation of PMI predicted by MLP regressor and the actual PMI')
plt.show()
</code>```

答:
Well, I found a mistake:

You train the model on samples, that weren't normalized:

nnref = MLPRegressor(...).fit(X_train, y_train)

But later you're trying to predict values from normalized samples:

nnref.score(X_train_norm, y_train)

Also the x and y axis should have values ranging from 0 to 180, which is not the case ( X from 20 to 100, y from -4100 to -3500)

Scikit-learn do not change values by itself. If X is not in range you need, it means that you've changed it somehow. Or, maybe your vision of X values is incorrect.

Body:
I am building a neural network with my research data in two ways: with a statistical programm (SPSS) and with python.
I am using the scikit learn MLPRegressor. The problem I have is that whereas my code is , apparently, well written (because it runs), the results do not make sense. The r2score should be around 0.70 ( it is-4147.64) and the correlation represented in the graph should be almost linear. (it is just a straight line at a constant distance from X axis).  Also the x and y axis should have values ranging from 0 to 180, which is not the case ( X from 20 to 100, y from -4100 to -3500)

If any of you can give a hand I would really appreciate it.
Thank you!!!!!!

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

from sklearn import neighbors, datasets, preprocessing
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import r2_score

vhdata = pd.read_csv('vhrawdata.csv')
vhdata.head()

X = vhdata[['PA NH4', 'PH NH4', 'PA K', 'PH K', 'PA NH4 + PA K', 'PH NH4 + PH K', 'PA IS', 'PH IS']]
y = vhdata['PMI']

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import Normalizer
scaler = Normalizer().fit(X_train)
X_train_norm = scaler.transform(X_train)
X_test_norm = scaler.transform(X_test)

nnref = MLPRegressor(hidden_layer_sizes = [4], activation = 'logistic', solver = 'sgd', alpha = 1,
                     learning_rate= 'constant', learning_rate_init= 0.6, max_iter=40000, momentum=
                     0.3).fit(X_train, y_train)

y_predictions= nnref.predict(X_test)

print('Accuracy of NN classifier on training set (R2 score): {:.2f}'.format(nnref.score(X_train_norm, y_train)))
print('Accuracy of NN classifier on test set (R2 score): {:.2f}'.format(nnref.score(X_test_norm, y_test)))

plt.figure()
plt.scatter(y_test,y_predictions, marker = 'o', color='red')
plt.xlabel('PMI expected (hrs)')
plt.ylabel('PMI predicted (hrs)')
plt.title('Correlation of PMI predicted by MLP regressor and the actual PMI')
plt.show()


问:
Authorization header missing in django rest_framework, is apache to blame?
I've managed to extend TokenAuthentication and I have a working model when using the request session to store my tokens, however when I attempt to pass Authorization as a header parameter as described here, I noticed that my Responses come back without the META variable HTTP_AUTHORIZATION. I also noticed that if I pass "Authorization2" as a header parameter that it is visible in the request:

```<code>{
    '_content_type': '',
    'accepted_media_type': 'application/json',
    '_request': <WSGIRequest
        path:/api/test_auth/,
        GET:<QueryDict: {}>,
        POST:<QueryDict: {}>,
        COOKIES:{
            'MOD_AUTH_CAS_S': 'ba90237b5b6a15017f8ca1d5ef0b95c1',
            'csrftoken': 'VswgfoOGHQmbWpCXksGUycj94XlwBwMh',
            'sessionid': 'de1f3a8eee48730dd34f6b4d41caa210'
        },
        META:{
           'DOCUMENT_ROOT': '/etc/apache2/htdocs',
           'GATEWAY_INTERFACE': 'CGI/1.1',
           'HTTPS': '1',
           'HTTP_ACCEPT': '*/*',
           'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
           'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
           'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
           'HTTP_AUTHORIZATION2': 'Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4c',
           ...
</code>```

My first guess is that the authorization header is being removed by apache, and I have read a few S/O questions that state that apache will throw out the value if it does not match basic authorization and authenticate, but I have no idea how to allow the Authorization header to 'pass through' to Django and the WSGIRequest. Does anyone know how to solve this problem?

I also use mod_auth_cas and mod_proxy, if that changes anything..

答:
The issue is the underscore in the HTTP header HTTP_AUTHORIZATION. Most webservers just ignores the headers with underscores.

Django dev server also exhibits the same, omitting headers with underscores.

This is the reason why Authorization2 works.

A Quick work around is to replace _ underscores in headers with - dashes,

Ex. changing the HTTP_AUTHORIZATION to HTTP-AUTHORIZATION

Body:
I've managed to extend TokenAuthentication and I have a working model when using the request session to store my tokens, however when I attempt to pass Authorization as a header parameter as described here, I noticed that my Responses come back without the META variable HTTP_AUTHORIZATION. I also noticed that if I pass "Authorization2" as a header parameter that it is visible in the request:

{
    '_content_type': '',
    'accepted_media_type': 'application/json',
    '_request': <WSGIRequest
        path:/api/test_auth/,
        GET:<QueryDict: {}>,
        POST:<QueryDict: {}>,
        COOKIES:{
            'MOD_AUTH_CAS_S': 'ba90237b5b6a15017f8ca1d5ef0b95c1',
            'csrftoken': 'VswgfoOGHQmbWpCXksGUycj94XlwBwMh',
            'sessionid': 'de1f3a8eee48730dd34f6b4d41caa210'
        },
        META:{
           'DOCUMENT_ROOT': '/etc/apache2/htdocs',
           'GATEWAY_INTERFACE': 'CGI/1.1',
           'HTTPS': '1',
           'HTTP_ACCEPT': '*/*',
           'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
           'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
           'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
           'HTTP_AUTHORIZATION2': 'Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4c',
           ...

My first guess is that the authorization header is being removed by apache, and I have read a few S/O questions that state that apache will throw out the value if it does not match basic authorization and authenticate, but I have no idea how to allow the Authorization header to 'pass through' to Django and the WSGIRequest. Does anyone know how to solve this problem?

I also use mod_auth_cas and mod_proxy, if that changes anything..


问:
How to simulate a slow internet connection for testing a webpage?
I am working on a prototype website on localhost using NodeJS and MongoDB.

I want to see how my site will load on slow internet.

How can I replicate that with localhost?

答: If you use google chrome, press F12, go to Network and go to online and select some speed.


答: Chrome dev tool will help you to do that.

Title: How to simulate a slow internet connection for testing a webpage?

Body:
I am working on a prototype website on localhost using NodeJS and MongoDB.

I want to see how my site will load on slow internet.

How can I replicate that with localhost?


问:
What Defines Cipher Grades?
I've been searching for what exactly defines different encryption "cipher grades" - such as those used in SSL and TLS, but haven't been able to find a specific resource that draws the line between them.

What defines LOW, MEDIUM, and STRONG cipher grades?

答: There are many factors that contribute to the security level (grade is rarely used for this term) of ciphersuites. Many algorithms are involved, e.g. different algorithms for key exchange (RSA or Diffie-Hellman), other algorithms for the confidentiality part (AES, RC4 etc) and even more for message authentication. There is no uniform classification that I know of except for the ciphersuites in the SuiteB profile. In GnuTLS we have also a classification based on the long term key sizes.</p>

Title: What Defines Cipher Grades?


问:
Wrong answer given by a julia code for project euler 29
I was trying to solve Project Euler Q.29 in julia and I am getting a wring answer.

Here is the problem statement:

Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:

2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:

4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
```

<p>Here is my code, its pure brute force.</p>

```powers = []

n = 100

for a in collect(2:n)
    for b in collect(2:n)
        append!(powers,a^b)
    end
end

length(unique(powers))
```

The correct answer is 9183 but I am getting 6143 as the answer.

Can someone please help me with this?

答:
You're suffering from integer overflow - see the manual here:

```<code>julia> 2^62
4611686018427387904

julia> 2^63
-9223372036854775808
</code>```

You can overcome the issue by using BigIntegers like so:

```<code>powers = []

n = 100

for a in collect(2:n)
    for b in collect(2:n)
        # note the `big()` here
        append!(powers,big(a)^b)
    end
end

length(unique(powers))
</code>```

Body:
I was trying to solve Project Euler Q.29 in julia and I am getting a wring answer.

Here is the problem statement:

Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:

2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:

4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?

Here is my code, its pure brute force.

powers = []

n = 100

for a in collect(2:n)
    for b in collect(2:n)
        append!(powers,a^b)
    end
end

length(unique(powers))

The correct answer is 9183 but I am getting 6143 as the answer.

Can someone please help me with this?

Body:
You're suffering from integer overflow - see the manual here:

julia> 2^62
4611686018427387904

julia> 2^63
-9223372036854775808

You can overcome the issue by using BigIntegers like so:

powers = []

n = 100

for a in collect(2:n)
    for b in collect(2:n)
        # note the `big()` here
        append!(powers,big(a)^b)
    end
end

length(unique(powers))