text:
Q: Как программно очистить поле типа integer в sql запросе? Имеется таблица access. Подключена через делфи. Пытаюсь очистить поле через запрос SQL, однако выпадает ошибка о несоответствии типов данных.
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add('UPDATE по_учет SET ПК=:q WHERE код=:w ');
ADOQuery1.Parameters.ParamByName('q').Value := '';
ADOQuery1.Parameters.ParamByName('w').Value := DBGridEh1.DataSource.DataSet.Fields.Fields[0].text;

A: Установить в 0 или NULL если второй не запрещен:
ADOQuery1.Parameters.ParamByName('q').Value := 0;
ADOQuery1.Parameters.ParamByName('q').Value := null;


text:
Q: Wet Sponge or Brass Sponge for solder tip cleaning? There seems to be a lot of differing opinions out there on what is best practice. A lot of people seem to be shying away from the wet sponge due to the thermal stress it imposes on the tip. I have personally always used the brass sponge only, but my Hakko station came with both a "wet" sponge and a brass sponge for cleaning.
What are the differences between the two cleaning devices? How should I decide which one to use given the type of work I do?

A: I didn't know the rationale for brass until a decade ago.
The story goes "wet sponge thermal shock cracks the iron plating eventually, then the tip fails"
I think my tips have lasted much longer since using brass sponge.
It is every bit as good at cleaning the tip as sponge.
I do find I use the hakko tip cleaner button far more with lead-free solders than was needed with tin-lead.

A: Tips cost less than the time wasted on fighting with tools that don't work well. Thermal stress cracks vs abrasion are ultimately completely irrelevant.
Bottom line is that brass is easier, faster, always ready, and cleans the tip better.
I've never seen a tip fail due to reasons  that I could confidently blame on a wet sponge or brass. But even if brass conclusively caused a tip to wear down 10x faster I would still use it. Make sure you consider all the costs, including your time and work quality, when making a decision.

A: Here's a huge con I've noticed when using brass wool:
When pressing the iron into the brass, it gives/bends. When you pull away, the brass then springs back into place. Why is that bad? Because there may be hot, liquid metal on that brass!
There is a potential hazard to both the project you are working on (think small, unseen shorts), or a safety issue to the face.
I have personally seen my brass wool fling solder into the air and splash onto a PCB of mine. I've stopped using it ever since. Even if I try to be careful, I don't see it worth the risk when the sponge works well enough.

A:
What are the differences between the two cleaning devices? How should I decide which one to use given the type of work I do?

When you have a lot of flux or contaminates, a wet sponge cleans it quickly. The brass sponge is ok, but it seems you do have to train it so it doesn't splatter the solder, but stabbing motions into it seem to not splatter the solder compared to just laying it on top of it and rolling the iron like you do on a wet sponge.
I know some people adopted the rule no-clean : brass sponge and flux and low flux: wet sponge. Their reasoning behind it was the flux accumulates in the brass sponge where it washes away with the wet sponge.
Either way, it doesn't matter to me personally as long as it works.

A: Wet sponge: Cheaper, less abrasive.
Brass wool: Removes "debris" better, smaller thermal shock (drop of temperature can be more of an issue than cracks/wear depending on your iron), you don't have to pour water whenever you start soldering.
I personally prefer the brass wool, cleans better, no water pouring, doesnt affect the temperature of the tool so much (although it still drops it a bit).

A: I didn't consider this an answer, but here's what life taught me so far (as per recommendation from @pipe): I think it's a matter of preference, however, I have to say that I have never, ever, seen a cracked tip due to wet sponge. That doesn't mean that it can't happen. Brass sponge isn't prefect, either, as it may wear out your tip faster due to being more abrasive, but this, too, I haven't seen in practise (but it's also true I I haven't seen more than a few). When in doubt, test for yourself, that's the best way to find out any answer.

A: Brass sponge has the mentioned advantage of not adding thermal stress to the tip when it cools, so it supposedly gives longer tip life. Other than that, it is mostly useful when you work with larger tips and need to remove large amounts of solder from the tip.
The downside of brass sponge is that it doesn't clean the tip 100%. There's almost always some solder remaining after using it. Which is normally a good thing, except when working with small/fine-pitch components (<0603 or <0.5mm pitch). If you have solder residue on the tip when doing such joints, it will mess everything up, so brass sponge isn't even an option for fine pitch work.
Also I find that tip life is mostly about using quality equipment with good temperature control, as well as avoiding polluting the tip. (Bumping into plastic surfaces of connectors, soldering onto lacquered surfaces etc. And stop using the solder iron for heating shrink tubes!) Covering the tip in solder when done working likely does far more for tip life than brass sponge vs wet sponge. I've had Metcal  tips lasting over a year even though I exclusively used wet sponge.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get mssql_connect to work on windows 7 I have mssql_* functions working on my Ubuntu installation and want to duplicate this on my windows 7 box.  I have installed wamp on the win7 box, but I cannot get it to see the mssql_* functions.  I have read many posts about nothing is working.  I have the ext directory properly set.  I have extension=php_mssql.dll  do not see the mssql section in phpinfo, but I do see sqlsrv section.   I would like my prod and test environment to match.
Thanks in advance for any assistance
Dean-O

A: I just checked my local wampserver 2.1 installation, and although there's an option to enable the php_mssql extension, it's missing from the extensions directory.
You can try the FreeTDS extension, which supposedly works fine under both *nix and Windows.
The Moodle wiki specifies that the Microsoft SQL Server driver has "known problems":

WARNING: This driver has known problems and is therefore not suitable
  for any Moodle production servers.

and recommends the use of FreeTDS instead (by installing the php_dblib extension). Moodle is a known user of MSSQL, and a respected project, but they don't really specify what they mean by "known problems", so you can take this with a grain of salt...
http://docs.moodle.org/24/en/Installing_MSSQL_for_PHP
If FreeTDS doesn't work for you, you can try installing the official Microsoft drivers:
http://www.microsoft.com/en-us/download/details.aspx?id=20098


text:
Q: i am using animation-iteration-count property for left to right animation how can i remove or hide the div once the animation is over i am using animation-iteration-count property in css for left to right animation how can i remove or hide  the div once the animation is over at the ending point i.e, it should be removed from left to right with animation once reached 100%.
same as we see picture in gallery app
does its have any such property.
pls i need the solution only in css.
below is my code
<!DOCTYPE html>

Note: The animation-iteration-count property is not       supported in Internet Explorer 9 and earlier versions.

thanks in advance.

A: You are looking for the animation-fill-mode css property. Use either both or forwards as a value.

The animation-fill-mode property specifies a style for the element
  when the animation is not playing (when it is finished, or when it has
  a delay).

More info here.

jsFiddle

CODE SNIPPET:

body {
  overflow: hidden;
  margin: 0;
}
div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  -webkit-animation: mymove 1s;
  /* Chrome, Safari, Opera */
  -webkit-animation-iteration-count: 0;
  /* Chrome, Safari, Opera */
  -webkit-animation-fill-mode: both;
  animation: mymove 1s;
  animation-iteration-count: 1;
  animation-fill-mode: both;
}
/* Chrome, Safari, Opera */

@-webkit-keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 100%;
  }
}
@keyframes mymove {
  from {
    left: 0px;
  }
  to {
    left: 100%;
  }
}

Note: The animation-iteration-count property is not supported in Internet Explorer 9 and earlier versions.


text:
Q: Lose EF Code First Migration when working on different TFS branches? We are using TFS and have different branches for our Dev.

*

*in the branch A we made a migration to change a column size

*in the branch B we made a migration to add a new table. This branch doesn not know about the branch A modification !!

*both modification are merged to the main branch.
When I do an update database, it does the 2 migration but at the end tells me there is pending changes. If I do an Add-Migration, it creates the same as the 1st migration (in branch A).

Unable to update database to match the current model because there are pending
      changes and automatic migration is disabled. Either write the pending model
      changes to a code-based migration or enable automatic migration. Set
      DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic
      migration.
      You can use the Add-Migration command to write the pending model changes to a
      code-based migration.

Is it because something is missing in  the content of the property Target de IMigrationMetadata of my last migration since it didn't know about the 1st one ?
Is it possible to handle migrations in different TFS branches?

A: An EF migration step contains a metadata file, that has a signature of the model that is the result of the migration step. The problem when merging is that the signature of the migration done in branch B doesn't include the stuff done in the migration in branch A. As long as the migrations are in the branches, this is correct. When merging it becomes wrong.
To remedy it, you have to regenerate the meta-data of the latter migration with
add-migration MyMigrationName

Running add-migration on an existing migration without the -force parameter will regenerate just the metadata.
I wrote an in depth walk-through of a merging scenario in the EF Migrations and a Merge Conflict post on my blog.

A: As an addition to Anders Abel's answer and for those of you who are having the issue when trying to regenerate the last migrations metadata causing EF to create a separate migration with a 1 appended to it.
You must include the full date/time stamp.
E.g.
If the filename of your previous migration is 201701011322_MakeChangesToPotatoTable
Then you must include the fullname properly in the "Add-Migration" command.
I.E.
Add-Migration 201701011322_MakeChangesToPotatoTable

A: With EF core, the current state of the model is kept in ***ModelSnapshot.cs.  It is normally merged so you don't have anything to do... unless there is a conflict.


text:
Q: ASP.NET Core & Swagger : generate multiple outputs I'm using ASP.NET Core with Swashbuckle.AspNetCore.SwaggerGen in version v6.1.5.
I want routes like [HttpGet] or [HttpGet("user")] in a public swagger.json for public endpoints and other routes that contain internal inside the route like this [HttpGet("internal/user/{userGuid}")] to be in an internal instance of swagger.json endpoints.
I configure Swagger in startup in ConfigureServices like this:
services.AddSwaggerGen(gen =>
{
    gen.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Server API",
        Version = "1.0",
        Description = "This API features all public available endpoints showing different API features."
    });
    gen.SwaggerDoc("v1-internal", new OpenApiInfo
    {
        Title = "Viewer Server API (internal)",
        Version = "v1-internal",
        Description = "This API features all public available endpoints showing different API features."
    });
});

and in Configure
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Viewer Server API v1");
    c.SwaggerEndpoint("/swagger/v1-internal/swagger.json", "Viewer Server API v1 (internal)");
});

How can I get it to create a public and an internal swagger.json?

A: Filtering different version or in my case "visibility-layer" can be done like the follwing.
Configure Swagger in startup in ConfigureServices like this:
services.AddSwaggerGen(gen =>
{
    gen.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Server API",
        Version = "1.0",
        Description = "This API features all public available endpoints showing different API features."
    });
    gen.SwaggerDoc("v1-internal", new OpenApiInfo
    {
        Title = "Viewer Server API (internal)",
        Version = "v1-internal",
        Description = "This API features all public available endpoints showing different API features."
    });

    gen.DocInclusionPredicate((docName, apiDesc) =>
    {
        if (docName.Contains("internal"))
        {
            return apiDesc.RelativePath.Contains("internal/");
        }
        else
        {
            return !apiDesc.RelativePath.Contains("internal/");
        }
    });
});

and in Configure
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Viewer Server API v1");
    c.SwaggerEndpoint("/swagger/v1-internal/swagger.json", "Viewer Server API v1 (internal)");
});

And now you can choose different configurations like in the image below:


text:
Q: Regex for splitting sentences isn't working properly C# I am trying to write a regex which splits sentences in C#.
My regex isn't working properly, it splits them good, but the last character of the string is always removed. Any tips?
For example if I want to split text to sentences:
Lorem ipsum dolor sit amet. Nam autem doloribus ut perspiciatis omnis est ratione quidem!
My regex splits them into:
Lorem ipsum dolor sit ame
Nam autem doloribus ut perspiciatis omnis est ratione quide
It should be:
Lorem ipsum dolor sit amet
Nam autem doloribus ut perspiciatis omnis est ratione quidem

Sample code

My regex is string variable: patern

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace L4_17
{
    internal class Program
    {
        static void Main(string[] args)
        {
            const string firstBookData = "first.txt";
            string firstFileData = File.ReadAllText(firstBookData);
            string pattern = "[^\\.\\!\\?] *[\\.\\!\\?]";
            List<string> allSentencesInFirstDataFile = Regex.Split(firstFileData, pattern).ToList();
            foreach(string sentence in allSentencesInFirstDataFile)
            {
             Console.WriteLine(sentence);
            }

        }
    }
}

A: I suggest using different pattern:
[.!?]+\s*(?=\p{Lu}|$)

Explanation:
[.!?]+       - at least one symbol of ., !, ? (let's support ??, ..., ?! etc.)
\s*          - zero or more white spaces
(?=\p{Lu}|$) - either end of the string or Capital letter of the next sentence

Code:
var text = "Lorem ipsum dolor sit amet. Nam etc. autem??? Doloribus ut perspiciatis?! Omnis est ratione quidem!";

var lines = Regex.Split(text, @"[.!?]+\s*(?=\p{Lu}|$)");

Console.WriteLine(string.Join(Environment.NewLine, lines));

Output:
Lorem ipsum dolor sit amet
Nam etc. autem               # <- note etc. is not the end of the sentence
Doloribus ut perspiciatis
Omnis est ratione quidem


text:
Q: How I can solve error CS0201 in Unity to end the game? Good evening.
I want to ask about Unity's problem I met.
I made pong-like game and I made 2 scripts for turning game scene to the result when ball hits to the ball behind the plays, However when I insert them to the wall and GameManagement object, the error of "error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement" was come out.
I'd like to know any solution for this problem
Thank you.
Game management Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameMaster : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public void GameOver()
    {
        SceneManager.LoadScene("Result");
    }
}

Script for wall to Check hit or not
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameoverPlayer1 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    private void OnCollisionEnter(Collision collision){
        GameObject.Find("GameMaster").GetComponent<GameMaster>().GameOver;
    }
}

A: You need to call the GameOver as a Method.
GameObject.Find("GameMaster").GetComponent<GameMaster>().GameOver();

like this


text:
Q: Android SQLite - NullPointerException when trying to access single row yet can access data as a whole? Basically, I can insert into my database and view all the results using the below method and a SimpleCursorAdapter displaying to a ListView - works totally fine.
// Returns a Cursor containing all JSON strings
public Cursor getAllJSONstrings()
{
    // Return all JSONstrings ordered by COLUMN_ID
    return ssDatabase.query(TABLE_ROUTINES, new String[] {COLUMN_ROWID, COLUMN_JSON}, null, null, null, null, COLUMN_ROWID);
}

However, the following method gives nothing less than the NullPointerException every time I query.
The id LogCat tag shows the tag as being what it should be, 1 for the first item etc.
// Return one JSONstring in String form
public String getJSONstring(long id)
{
    Log.i(TAG, "getJSONstringStart... id=" + id);

    Cursor cursor;

    Log.i(TAG, "Cursor defined");

    /****** NullPointerException LINE ******/
    cursor = ssDatabase.query(TABLE_ROUTINES, null, "_id=" + id, null, null, null, null);

    Log.i(TAG, "Exceed Cursor");

    int index = cursor.getColumnIndex(COLUMN_JSON);

    Log.i(TAG, "index=" + index);

    return cursor.getString(index);
}

For what it's worth, this method getJSONString(long id) is being executed in an AsyncTask. The id it refers to is the id in an OnItemClickListeners onItemClick method.
Any help would be very appreciated, my head has gone square!
Cheers!

A: You have to do moveToFirst(). Your method is assuming that the cursor's current row pointer is already set to the first row and that getString(index) will return the value of COLUMN_JSON for the first row.
This isn't true. You should never assume that your query returned something. If the selection clause didn't return any rows, then cursor.getCount() will return 0. In addition, the query may throw a SQLite exception. Any time you look at the results of a query, you should enclose your code in
try {
// query
if ((cursor != null) && (cursor.getCount() > 0)) {

    // some operation

}
...

} catch (Exception e) {
}

A: Given that the only possible reference to be null is ssDatabase, since cursor is just being assigned and id is a plain long, and assuming that you are using the common SqlliteHelper pattern, my guess is that you may have forgotten to call open() before calling

getJSONstring


text:
Q: Does WordPress function get_post(post_id) query the database? In my WordPress theme the theme author first makes a database query to get all active posts to get post IDs like this:
$SQL = "SELECT post_id FROM mytable_postmeta
            WHERE meta_key = 'expiry_date' AND CAST(meta_value AS DATETIME) >='2023-01-14 12:00:00'"
$posts_found = $wpdb->get_results($SQL, OBJECT);

Then he later loops over the results and get each posts by it's ID like this:
foreach($posts_found as $single_post){
    global $post;
    $post = get_post($single_post->ID);
}

My question is if this is a database query to get all post IDs and then one database query for each post in the foreach loop? I.e., does the get_post WordPress function query the database once per post in the loop?
If so, can I re-write this in a smart way to reduce the number of database calls?

A: Sure there is, try this:
$SQL = "SELECT post_id FROM mytable_postmeta
            WHERE meta_key = 'expiry_date' AND CAST(meta_value AS DATETIME) >='2023-01-14 12:00:00'";

$post_ids = $wpdb->get_col($SQL);
$posts = get_posts([
    'include' => $post_ids,
    'post_status' => 'publish'
]);

or even better, using meta_query
$posts = get_posts([
    'meta_query' => [
        [
            'key' => 'expiry_date',
            'value' => '2023-01-14 12:00:00',
            'compare' => '>=',
            'type' => 'DATETIME'
        ]
    ],
    'post_status' => 'publish'
]);

Yes, get_post does perform an additional query each time it is called.


text:
Q: Best approach for 2D gesture recognition in VR? I'm the developer on a game which uses gesture recognition with the HTC Vive roomscale VR headset, and I'm trying to improve the accuracy of our gesture recognition.
(The game, for context: http://store.steampowered.com//app/488760 . It's a game where you cast spells by drawing symbols in the air.)
Currently I'm using the 1 dollar algorithm for 2D gesture recognition, and using an orthographic camera tied to the player's horizontal rotation to flatten the gesture the player draws in space.
However, I'm sure there must be better approaches to the problem!
I have to represent the gestures in 2D in instructions, so ideally I'd like to:
Find the optimal vector on which to flatten the gesture.
Flatten it into 2D space.
Use the best gesture recognition algorithm to recognise what gesture it is.
It would be really good to get close to 100% accuracy under all circumstances. Currently, for example, the game tends to get confused when players try to draw a circle in the heat of battle, and it assumes they're drawing a Z shape instead.
All suggestions welcomed. Thanks in advance.

A: Believe me or not, but I found this post two months ago and decided to test my VR/AI skills by preparing a Unity package intended for recognising magic gestures in VR. Now, I'm back with a complete VR demo: https://ravingbots.itch.io/vr-magic-gestures-ai

The recognition system tracks a gesture vector and then projects it onto a 2D grid. You can also setup a 3D grid very easily if you want the system to work with 3D shapes, but don't forget to provide a proper training set capturing a large number of shape variations.

Of course, the package is universal, and you can use it for a non-magical application as well. The code is well documented. Online documentation rendered to a PDF has 1000+ pages: https://files.ravingbots.com/docs/vr-magic-gestures-ai/
The package was tested with HTC Vive. Support for Gear VR and other VR devices is progressively added.

A: Seems to me this plugin called Gesture Recognizer 3.0 could give you a great insight on what step you should take
Gesture Recognizer 3.0
Also, I found this javascript gesture recognition lib in github
Jester
Hope it helps.

A: Personally I recommend AirSig
It covers more features like authentication using controllers.
The Vive version and Oculus version are free.
"It would be really good to get close to 100% accuracy under all circumstances." My experience is its built-in gestures is over 90% accuracy, signature part is over 96%. Hope it fits your requirement.


text:
Q: Не работает событие onSubmit. React Есть компонент формы с кнопкой:
export class Form extends Component {
  changeDateTextHandler = ({ target }) => {
    const { changeDateText } = this.props;
    changeDateText(target.value);
  }

  changeMoneyTextHandler = ({ target }) => {
    const { changeMoneyText } = this.props;

    if (target.value === '') {
      changeMoneyText('');
    }

    if (!+target.value) {
      return;
    }

    changeMoneyText(+target.value);
  }

  formHandler = (event) => {
    event.preventDefault();
    console.log('Hi');
  }

  addItemHandler = (event) => {
    event.preventDefault();

    const { addItem, currentInputData, clearInputFields } = this.props;
    addItem({
      id: uniqueId(),
      category: {
        categoryName: 'Start value',
        categorySign: '',
      },
      date: currentInputData.dateText,
      money: +currentInputData.moneyText,
    });
    clearInputFields();
  }

  render() {
    const { list, currentInputData } = this.props;

    const renderStartButton = () => (
      (list.length || !(currentInputData.dateText && currentInputData.moneyText)) ? (
        <button type="button" className="btn btn-add_disabled">Add start value</button>
      ) : (
        <button type="button" onClick={this.addItemHandler} className="btn btn-add">Add start value</button>
      )
    );

    return (

        <form onSubmit={this.formHandler}>

                <input type="text" className="form-control" placeholder="Date" value={currentInputData.dateText} onChange={this.changeDateTextHandler} />

                <input type="text" className="form-control" placeholder="Money" value={currentInputData.moneyText} onChange={this.changeMoneyTextHandler} />

        </form>
        {renderStartButton()}

    );
  }
}

Хочу повесить на кнопку и на форму схожие обработчики, чтобы при нажатие на enter/кнопку происходило одно и тоже действие. Но не могу понять, почему не работает событие onSubmit на форме.

A: *

*Добавить {renderStartButton()} в форму

*<button type="submit"


text:
Q: Combobox SelectionChangedEvent doesn't write to class field I have a problem with writing data to class field. I declared field "rcbSelection" and then initialize it in Page_load(). Then I try to add data in it in some combobox SelectionChangedEvents.
public partial class AddToProcurementPlan : Page
{
    Dictionary<string, int?> rcbSelection;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            rcbSelection = new Dictionary<string, int?>();
            /*other code*/
        }
     }

    protected void rcb_FinancingBudget_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox rcb = (RadComboBox)sender;
        if (rcbSelection.ContainsKey("financingbudget"))
            rcbSelection["financingbudget"] = int.Parse(rcb.SelectedValue);
        else
            rcbSelection.Add("financingbudget", int.Parse(rcb.SelectedValue));
    }

    protected void rcb_BudgetName_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox rcb = (RadComboBox)sender;
        if (rcbSelection.ContainsKey("budget"))
            rcbSelection["budget"] = int.Parse(rcb.SelectedValue);
        else
            rcbSelection.Add("budget", int.Parse(rcb.SelectedValue));
    }

    protected void rcb_FondName_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox rcb = (RadComboBox)sender;
        if (rcbSelection.ContainsKey("fond"))
            rcbSelection["fond"] = int.Parse(rcb.SelectedValue);
        else
            rcbSelection.Add("fond", int.Parse(rcb.SelectedValue));
    }

    protected void rcb_Kfkr_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox rcb = (RadComboBox)sender;
        if (rcbSelection.ContainsKey("kfk"))
            rcbSelection["kfk"] = int.Parse(rcb.SelectedValue);
        else
            rcbSelection.Add("kfk", int.Parse(rcb.SelectedValue));
    }

    protected void rcb_Kekr_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox rcb = (RadComboBox)sender;
        if (rcbSelection.ContainsKey("kekr"))
            rcbSelection["kekr"] = int.Parse(rcb.SelectedValue);
        else
            rcbSelection.Add("kekr", int.Parse(rcb.SelectedValue));
    }

    protected void rcb_BudgetExec_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox rcb = (RadComboBox)sender;
        if (rcbSelection.ContainsKey("budgetexec"))
            rcbSelection["budgetexec"] = int.Parse(rcb.SelectedValue);
        else
            rcbSelection.Add("budgetexec", int.Parse(rcb.SelectedValue));
    }

    protected void rcb_SectionCode_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox rcb = (RadComboBox)sender;
        if (rcbSelection.ContainsKey("section"))
            rcbSelection["section"] = int.Parse(rcb.SelectedValue);
        else
            rcbSelection.Add("section", int.Parse(rcb.SelectedValue));
    }

    protected void rcb_TargetArticle_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        RadComboBox rcb = (RadComboBox)sender;
        if (rcbSelection.ContainsKey("targetarticle"))
            rcbSelection["targetarticle"] = int.Parse(rcb.SelectedValue);
        else
            rcbSelection.Add("targetarticle", int.Parse(rcb.SelectedValue));
    }
}

But when I set stop point on last event I can see that rcbSelection is empty. What i doing wrong? Help me please.

A: I suspect your rcbSelection dictionary is being reset after the postbacks of your SelectedIndexChanged events since the dictionary isn't being persisted in some sort of in memory storage like ViewState.
Consider persisting your rcbSelection dictionary like...

        private Dictionary<string, int?> rcbSelection
        {
            get
            {
                if(this.ViewState["rcbSelection"] != null)
                {
                    return (Dictionary<string, int?>)this.ViewState["rcbSelection"];
                }

                return new Dictionary<string, int?>();
            }

            set
            {
                this.ViewState["rcbSelection"] = value;
            }
        }

Also in your page_load event if you don't want the dictionary to be reset after each postback consider removing rcbSelection = new Dictionary<string, int?>(); from your page_load function or initializing only once by checking if it's the first page load by...
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                rcbSelection = new Dictionary<string, int?>();
            }

            // other postback code here ...
        }

Hope that helps.


text:
Q: HTML file input on iOS - accept images and videos I want to implement a HTML file input to let the user shoot a picture or a video. I define the allowed formats via accept attribute:
<input type="file" id="sentFile" accept="image/*,video/*">

If I click on the input, iOS 9 shows me a modal, where I'm able to "Record picture or video". After clicking on that button, the camera app opens and I'm able to take a picture, but can't record a video.
If I define a single input with video only, f.e.:
<input type="file" id="sentFile" accept="video/*">

I'm able to record a video.
Why is the first one not working on iOS?

A: try this
accept="image/*;video/*;capture=camcorder"

A: Have you set the Privacy - Camera Usage Description in your ios application?
You need to add that permission if you want to take a photo in your application.


text:
Q: use selector search on html code(string) on PHP variable or ways alike what im currently doing is i have a text area for user to copy and paste the html code.
i want to get a certain element of that html file.
in pure html, this can be done via jquery selector
but i think its a whole different thing when html code is on a variable and considered as a string.
how can i get a certain element location in that way?
code is:
        function searchHtml() {
            $html = $_POST; // text area input contains html code
            $selector = "#rso > div > div > div:nth-child(1) > div > h3 > a"; //example - the a element with hello world
            $getValue = getValueBySelector($selector);  //will return hello world
        }
        function getValueBySelector($selector) {
            //what will i do here?
        }
        searchHtml();

A: You can look at SimpleHTMLDom Parser (manual at http://simplehtmldom.sourceforge.net/manual.htm). This is a powerful tool to parse the HTML code to find and extract various elements and their attribute.
For your particular case, you can use
// Create a DOM object from the input string
$htmlDom = str_get_html($html);
// Find the required element
$e = $htmlDom->find($selector);

Oh, and you've to pass the provided input value to the getValueBySelector() function :-)


text:
Q: THREE: Using worldmap.svg as material on sphere but there are too many pixels, how do i reduce them? I am using an svg so I can color single countries.
I know WebGL doesn't support svg, thats why it gets pixeled but the borderlines are pixeled too much, any idea how I can make it look better?
"THREE.WebGLRenderer: Texture has been resized from (2000x1001) to (1024x512)"?
The image gets cropped, is that the problem?

                var renderer = new THREE.WebGLRenderer();
                renderer.setSize( window.innerWidth, window.innerHeight );
                document.body.appendChild( renderer.domElement );

                let scene = new THREE.Scene();

                var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

                var geometry = new THREE.SphereGeometry( 5,32,32 );
                let texture = new THREE.TextureLoader().load("/img/world-background.5375a735.svg");
                var material = new THREE.MeshBasicMaterial( { map: texture, color: "white"} );
                var sphere = new THREE.Mesh( geometry, material );
                sphere.rotation.y = 4.5;
                sphere.rotation.x = 0.5;

                scene.add( sphere );

A: To avoid the resize, try to set the minFilter property of your texture to THREE.LinearFilter. This should noticeably improve the final texture resolution in your case. Alternatively, you can try to change your texture to POT (power-of-two) by default. That would mean using a resolution like 2048x1024.
three.js R112


text:
Q: How to skip items in a dictionary I have a list of dictionaries(over a thousand) from an API response that I reordered based on some other logic. Each list of dict's has an ID. My goal is to update the ID to start at 0 again and increment 1 for each list.
Here is an example of what I have:
list_of_dicts = [
 {
  'id':   5,
  'age': 22,
  'name': 'Bryan'
 },
 {
  'id':   0,
  'age': 28,
  'name': 'Zach'
 },
]

And what I need:
list_of_dicts = [
 {
  'id':   0,
  'age': 22,
  'name': 'Bryan'
 },
 {
  'id':   1,
  'age': 28,
  'name': 'Zach'
 },
]

Below is my current code. I keep getting an error of 'int' object has no attribute 'update' or a str error, probably because it's iterating past id.
Combined holds my list of dictionaries.
    counter = 0
    for i in combined:
        for k,v in i.items():
            if k == 'id':
                v.update({'id': counter})
                counter += 1
            else:
                continue

Can someone guide me on where I'm going wrong at?

A: You don't need a nested loop to update the id element of the dictionary. Just index it directly.
for i, d in enumerate(list_of_dicts):
    d['id'] = i

A: If you have a list of dicts then you could iterate over list enumerating and change the ids:
for i,di in enumerate(list_of_dicts):
     di['id'] = i


text:
Q: Prove a particular random process is weakly stationary Let $\left(X_i\right)_{i\ge1}$ be independent identically distributed random variables such that $\mathrm{P}\left( X_i = -1 \right)=\mathrm{P}\left( X_i = 1 \right)=\frac{1}{2}$.
Let  $X(t)=X_{\left \lfloor t \right \rfloor}$ be a stochastic process such that the initial time follows $U\left( 0,1 \right)$.
Prove the process is weakly stationary.
EDIT: to completely change the previous version of the definition which was bogus:
$X(t)=X_{\left \lfloor t_0+t \right \rfloor}$ where $t_0\in\mathrm{U}\left(0,1\right)$
======================================================
So far I have proved that:
$m_X(t)=0$
$\mathrm{E}\left( X(t)X(t') \right) = \left\{\begin{array}{c} 1\quad\text{if $\left \lfloor t \right \rfloor = \left \lfloor t' \right \rfloor$ }\\0\quad \text{otherwise} \end{array} \right.$
So for the moment it is not weakly stationary since the autocorrelation depends not only on $t'-t$, but also on whether there is an integer between $t$ and $t'$. I can't find a way to use the uniform distribution.
I have tried the following:
If $|\tau|=\left| t'-t\right|>1$, then $\left \lfloor t \right \rfloor \neq \left \lfloor t' \right \rfloor$. So $\mathrm{E}\left( X(t)X(t') \right) =0$
If $|\tau|=\left| t'-t\right|\leq1$, and assuming, without loss of generality, that $ t=t_0+t_1 \leq t_0+t_2=t'$, I want to prove that $\mathrm{P}\left(\left \lfloor t \right \rfloor \neq \left \lfloor t' \right \rfloor\right)$ is a function of $\tau$.
$\mathrm{P}\left(\left \lfloor t \right \rfloor \neq \left \lfloor t' \right \rfloor\right) = \mathrm{P}\left( \exists k\in\mathbb{N}/k\in\left[t,t'\right] \right) = \mathrm{P}\left(  \exists k\in\mathbb{N}/ t_0\in \left[k-t_2,k-t_1 \right] \right)$
Here I have an issue because I don't know if such probability is a function of $\tau$.


text:
Q: Jasmine Spy Undefined When I run my jasmine specs I get the following error:
Error: Expected a spy, but got undefined.

My coffeescript code:
  describe "setupForm", ->
    beforeEach ->
      spyOn(Subscription.prototype, 'runSimulation')

    it "calls subscription.runSimulation when form is submitted with number", ->
      Subscription.prototype.runSimulation()
      expect(Subscription.prototype.runSimulation()).toHaveBeenCalled()

I have simplfied my erroring code to the above for debugging, but I can't figure out why it is saying the spy is never called when I'm explicitly calling it my test. I am testing the method in other places, so I think the error has to be with how I am using the Jasmine Spy.  Thanks.

A: Take the () off the end of Subscription.prototype.runSimulation():
  expect(Subscription.prototype.runSimulation).toHaveBeenCalled()


text:
Q: Count distinct number of customers per fiscal year and display all dates in query result DB-Fiddle
CREATE TABLE customers (
    id SERIAL PRIMARY KEY,
    order_date DATE,
    customerID VARCHAR(255)
);

INSERT INTO customers
(order_date, customerID
)
VALUES
('2020-01-15', 'Customer_01'),
('2020-02-03', 'Customer_01'),
('2020-02-15', 'Customer_01'),
('2020-03-18', 'Customer_01'),
('2020-03-20', 'Customer_01'),
('2020-04-22', 'Customer_01'),
('2021-01-19', 'Customer_01'),

('2020-01-25', 'Customer_02'),
('2020-02-26', 'Customer_02'),
('2020-11-23', 'Customer_02'),
('2021-01-17', 'Customer_02'),
('2021-02-20', 'Customer_02');

Expected Result:
order_date   |      quantity
             |    (fiscal year)
-------------|----------------------------------------------------
2020-01-15   |           1   --> Customer_01 appears the first time between 2019-03 and 2020-02
2020-01-25   |           1   --> Customer_02 appears the first time between 2019-03 and 2020-02
2020-02-03   |           0
2020-02-15   |           0
2020-02-26   |           0
2020-03-18   |           1   --> Customer_01 appears the first time between 2020-03 and 2021-02
2020-03-20   |           0
2020-04-22   |           0
2020-11-23   |           1   --> Customer_02 appears the first time between 2020-03 and 2021-02
2021-01-17   |           0
2021-01-19   |           0
2021-02-20   |           0

In the above result I want to list all order dates and count the number of customers distinct per fiscal year.
The fiscal year starts two months after the calender year and therefore goes from March to February.
(e.g. from 2020-03 til 2021-02).
For example Customer_01 appears the first time on 2020-03-18 within the fiscal year 2020-03 til 2021-02.
Therefore, this order_date gets assigned 1 to it.
If the customer appears again within the fiscal year the next order_date will get assigned 0 to it.

With reference to this question in MariaDB I was able to achieve the expected result as you can see in the DB-Fiddle.
However, now I want to get the same results using postgresSQL.
Therefore, I have modified the query so far to this:
SELECT
order_date,
SUM(rn = 1) AS quantity
FROM

  (SELECT
  order_date,
  row_number() over(PARTITION BY DATE_PART('year', (order_date - INTERVAL '2 month')::date), customerID ORDER BY order_date) rn
  FROM customers
  ) t

GROUP BY 1;

However, now I am getting an error function sum(boolean) does not exist on the SUM(rn = 1) part.
What is the equivalnt syntax for the SUM(rn = 1) in postgresSQL to achieve the expected result?

A: There are two parts to this problem.  One is determining the fiscal year.  The second is doing the distinct count.
The first is solved by subtracting two months and extracting the date.  The second is logically:
select c.*,
       count(distinct customerId) over (partition by fyyyy order by order_date)
from (select c.*, date_trunc('year', order_date - interval '2 month') as fyyyy
      from customers c
     ) c
order by date;

Unfortunately, this doesn't work in Postgres.  But you can instead just count the first time that a customer appears:
select c.*,
       count(*) filter (where seqnum = 1) over (partition by fyyyy order by order_date)
from (select c.*,
             date_trunc('year', order_date - interval '2 month') as fyyyy,
             row_number() over (partition by customerId, date_trunc('year', order_date - interval '2 month')
                                order by order_date
                               ) as seqnum
      from customers c
     ) c
order by order_date;

Here is a db<>fiddle.

A: After further investigation I came up with the following solution:
DB-Fiddle
SELECT
order_date,
(CASE WHEN t.rolling_count > 1 THEN 0 ELSE t.rolling_count END) AS quantity
FROM

  (SELECT
  order_date,
  (row_number() over(PARTITION BY DATE_PART('year', (order_date - INTERVAL '2 month')::date), customerID ORDER BY order_date)) AS rolling_count
  FROM customers
  ORDER BY 1
  ) t

GROUP BY 1,2
ORDER BY 1;

As comparison here is the MariaDB of the query:
SELECT
order_date,
(CASE WHEN t.rolling_count > 1 THEN 0 ELSE t.rolling_count END) AS quantity
FROM

  (SELECT
  order_date,
  (row_number() over(PARTITION BY YEAR(order_date - INTERVAL 2 MONTH), customerID ORDER BY order_date)) AS rolling_count
  FROM customers
  ORDER BY 1
  ) t

GROUP BY 1
ORDER BY 1;


text:
Q: Merging two sorted lists returns Runtime Error I am trying to solve a problem which asks for merging two sorted linked lists. Although my code passes most tests, it does not do well with large inputs, very long linked lists. What can i improve? Thanks!
This is my code:
#
# For your reference:
#
# SinglyLinkedListNode:
#     int data
#     SinglyLinkedListNode next
#
#
def mergeLists(head1, head2):
    if head1 is None:
        return head2
    if head2 is None:
        return head1

    p1=head1
    p2=head2
    while head1.data >= p2.data:
        nxt = p2.next
        p2.next = head1
        head1 = p2
        p2 = nxt
    p1 = head1
    while p1 is not None and p2 is not None:

        if p1.data <= p2.data and (p1.next is None or p1.next.data >= p2.data):

            next2 = p2.next
            p2.next = p1.next
            p1.next = p2
            p2 = next2

        p1 = p1.next
    return head1

A: It looks like you are do a lot of duplicate assignments, as well as duplicate checks. I tried to write a code with a minimal amount of both. Of course, if the goal was to write easy-to-read code, then a recursive algorithm would be the best solution. But not in our case. Also note that it makes no sense to check the sentinel on two lists at the same time, since the length of the lists is unknown and can be different at any time.
class L(object):
    __slots__ = 'data', 'next'

    def __repr__(self): # just for tests
        return f'{self.data!r}, {self.next!r}'

    def __eq__(self, other): # just for tests
        return (self.data == other.data) and (self.next == other.next)

def merge0(a: L, b: L, sentinel=None):
    if a is sentinel:
        return b
    if b is sentinel:
        return a

    if a.data > b.data:
        head = last = b
        b = b.next
    else:
        head = last = a
        a = a.next

    while True:
        if a.data > b.data:
            last.next = last = b
            if (b := b.next) is sentinel:
                last.next = a
                return head
        else:
            last.next = last = a
            if (a := a.next) is sentinel:
                last.next = b
                return head

The code above operates with 6 main pointers:

*

*a - the head of first linked list. a.next can be sentinel;

*b - the head of second linked list. b.next can be sentinel;

*head - the head of new merged linked list. It is either a or b. Not useful during the main loop;

*last - the current last object of new merged linked list. Initially is head;

*last.next - this pointer is undefined during the main loop. It can be a, b, a.next or b.next;

*sentinel - unique singleton object that marks the end of any linked list.

Each step of the loop, we find out smaller element and assign it to last.next. Then we create new last and check out possible end of the list with this element. Then the loop repeats.
However, this is still not an optimal algorithm. Imagine that we have ll1(0, 2, 3, 5, 5, 7, 8), ll2(6, 7, 9, 10) and merged ll(0, 2, 3, 5, 5, 6, 7, 7, 8, 9, 10). In fact, the first 5 elements of ll are the five elements of the ll1. According to the merge0 main loop, each of these elements (except the first) has been reassigned to its left neighbor. The inefficiency of this approach is especially notable when merged lists have a large spread in values.
Secondly, it would be nice to replace the explicit check of sentinel of each list. The sentinel object doesn't have to be None and may be implemented as a custom object with a native exception throwing mechanism.
Improved version:
@object.__new__
class sentinel(object):
    __slots__ = ()

    @property
    def next(self):
        raise self.Signal()

    @property
    def data(self):
        raise self.Signal()

    class Signal(Exception):
        pass

    def __eq__(self, other):  # just for tests
        return (other is self) or (other is None)

def merge1(a: L, b: L, sentinel=sentinel):
    if a is sentinel:
        return b
    if b is sentinel:
        return a

    if a.data <= b.data:
        head = x = a
        y = b
    else:
        head = x = b
        y = a

    try:
        while True:
            while (x := (last := x).next).data <= y.data:
                pass
            last.next = y
            while (y := (last := y).next).data <= x.data:
                pass
            last.next = x
    except sentinel.Signal:
        last.next = y if (x is sentinel) else x
        return head

Some test-related code:
def random_sorted_ll(length, min_num, span, sentinel=None):
    """creates sorted linked list of random integers"""
    assert length >= 1
    from random import randint
    from itertools import repeat

    head = last = L()
    head.data = d = randint(min_num, min_num + span)
    ll_factory = map(L.__new__, repeat(L, length-1))
    for l in ll_factory:
        last.next = last = l
        l.data = d = randint(d, d+span)

    last.next = sentinel
    # last.data should be close to (length * span / 2 + min_num)
    return head

def copy_ll(head, prev_sentinel=None, new_sentinel=None):
    """creates deepcopy of given linked list head with new sentinel"""
    if head is prev_sentinel:
        return new_sentinel
    head_copy = last = L()
    last.data = head.data
    head = head.next
    while head is not prev_sentinel:
        last.next = last = L()
        last.data = head.data
        head = head.next
    last.next = new_sentinel
    return head_copy

Some tests:
>>> j0 = random_sorted_ll(length=100, min_num=4, span=5)
>>> j1 = copy_ll(j0)
>>> j2 = copy_ll(j0, prev_sentinel=None, new_sentinel=sentinel)
>>> k0 = random_sorted_ll(length=111, min_num=4, span=5)
>>> k1 = copy_ll(k0)
>>> k2 = copy_ll(k0, prev_sentinel=None, new_sentinel=sentinel)
>>> (j0 == j1 == j2) and (k0 == k1 == k2)
True
>>> m0 = mergeLists(j0, k0)
>>> m1 = merge0(j1, k1)
>>> m2 = merge1(j2, k2)
>>> m0 == m1 == m2
True
>>> (m2 is j2) or (m2 is k2)
True

Comparisons:
def compare_speed(len0, len1, mn0, mn1, span0, span1):
    print(f'\nll in an approximate range ({mn0:_d}, {len0*span0//2+mn0:_d}) with {len0=:_d}')
    j0 = random_sorted_ll(len0, mn0, span0)
    j1 = copy_ll(j0)
    j2 = copy_ll(j0, None, sentinel)
    print(f'll in an approximate range ({mn1:_d}, {len1*span1//2+mn1:_d}) with {len1=:_d}')
    k0 = random_sorted_ll(len1, mn1, span1)
    k1 = copy_ll(k0)
    k2 = copy_ll(k0, None, sentinel)
    from timeit import timeit

    print('mergeLists:', timeit((lambda: mergeLists(j0, k0)), number=1), 'sec')
    print('merge0:', timeit((lambda: merge0(j1, k1)), number=1), 'sec')
    print('merge1:', timeit((lambda: merge1(j2, k2)), number=1), 'sec')

compare_speed(1_111_111, 1_000_000, 0, 0, 5, 5)
compare_speed(1_111_111, 1_000_000, 0, -25_000_000, 5, 100)
compare_speed(9_000_000, 9_111_111, 0, 0, 5, 5)

My results:
ll in an approximate range (0, 2_777_777) with len0=1_111_111
ll in an approximate range (0, 2_500_000) with len1=1_000_000
mergeLists: 0.46664454099999997 sec
merge0: 0.2180013780000003 sec
merge1: 0.16215903499999996 sec

ll in an approximate range (0, 2_777_777) with len0=1_111_111
ll in an approximate range (-25_000_000, 25_000_000) with len1=1_000_000
mergeLists: 0.4489969129999736 sec
merge0: 0.16649408400007815 sec
merge1: 0.1128580580000289 sec

ll in an approximate range (0, 22_500_000) with len0=9_000_000
ll in an approximate range (0, 22_777_777) with len1=9_111_111
mergeLists: 4.245676940000003 sec
merge0: 1.9906823259999982 sec
merge1: 1.548923153000004 sec

A: Here's how we do a merge operation by constructing a new list rather than modifying existing nodes:
def merge(p1, p2):
    while p1 is not None and p2 is not None:
        if p1.data < p2.data:
            yield p1.data
            p1 = p1.next
        else:
            yield p2.data
            p2 = p2.next

    while p1 is not None:
        yield p1.data
        p1 = p1.next

    while p2 is not None:
        yield p2.data
        p2 = p2.next

def mergeLists(p1, p2):
    return list(merge(p1, p2))

(Instead of yield, you can also .append() to a temporary list.)
If you must modify the nodes, you'll need to be a bit more careful that you don't modify anything you shouldn't be. Try using the method I proposed as a template.

A: def mergeLists(head1, head2):

  if not head1:
      return head2

  elif not head2:
      return head1

  if head1.data <= head2.data:
      res = head1
      res.next = mergeLists(head1.next, head2)
  else:
      res = head2
      res.next = mergeLists(head1, head2.next)

  return res


text:
Q: How to structure module with interactive methods I'm working on a program which parses data and presents it to users for annotation for the purpose of generating training data for an ML model. I'm looking for advice on how to structure this module's classes in the most logical way. I'm a bit new to OOP; abstracting beyond the typical "vehicle->car->car_brand" model of class inheritance is sort of where I find myself. The basic flow of this program is:

*

*Retrieve messy data from external source

*Parse data to create local representation which only contains information relevant to this task

*Present data to users, who then mark it up with annotations

*Generate statistics on those annotations

Should the interactive methods be part of the same class as the cleaned-up data? What about the methods to generate statistics?
I've tried subsuming all functionalities of this program under one class definition, which works fine but seems reductive and probably difficult for others to grasp quickly. Here is how I think the program might be structured (apologies for all the pseudo-code):
class AnnotationData:
    # has methods to retrieve messy data and smooth it into what humans need to see to do this task. Populates class attributes to represent that data.
class AnnotationMethods(AnnotationData):
    # has methods to interact with data
class AnnotationStatistics(AnnotationData):
    # has methods to generate statistics on data which has been augmented by humans

if __name__ == "__main__":
    # create base class
    # populate base class with messy data
    # smooth messy data into human-readable format
    # Instantiate AnnotationMethods class
    # Human does annotation
    # Instantiate AnnotationStatistics class
    # Return sweet sweet stats

Subsuming all of this into a single class works fine. I'm just wondering what the best practice is for divvying up methods which humans interact with from methods which just populate data.

A: Check this library https://github.com/dedupeio/dedupe. They have a similar workflow as yours.


text:
Q: Transmitting large data between two spring boot app I have two spring boot services names A and B.

*

*Service A receives a multipart file (which is huge in size > 100MB - 1GB in size).

*Service A needs to transmit the file to Service B (problem area)

*Service B performs some operation on data and return to Service A.

*Calls from A to B is sent using RestTemplate.

Problem Area

*

*Service A doesn't load the whole file in memory, but read from Multipart InputStream in chunks.

*Chunks are sent to B, rather a complete stream.

Is it possible to send the complete InputStream of multipart to service B, so that service A doesn't load the file as well as chunk the file over http/...(any other way)
(One way I had solved it to use fifo on the underlying linux platform and service A is writing continuously on a pipe and Service B is reading) - was looking someway to achieve it with http if possible.
Background - I want Service B to be in control of how much chunk they want and not Service A. It is because of the operation Service B perform - service B adds some additional bytes, so that when the reverse operation is performed on next data, it can see these additional bytes to understand how much more chunk should be read.
UPDATE OF THE GITHUB
I am not sure where I am getting it wrong? I pasted the complete project - https://github.com/robin-carry/large-data-transfer
The main files on client/server where all logic is below / README.md explains everything I am trying/failing to do...
client/src/main/java/com/lockdown/lazy/client/controller/UploadController.java
server/src/main/java/com/lockdown/lazy/server/controller/OpServiceController.java

A: Apache Http Client documentation talks about Request/Response entity streaming - see if that helps solve your scenario.

A: You can design interface with org.springframework.web.multipart.MultipartFile as argument, then- use it as feign client on sender side and implement it in controller on receiver side


text:
Q: How can i play a death animation on Unity? I want to play a death animation to my enemy. Basically, he has an idle animation and I would like to play the death animation when he dies, and after one or two seconds, the GameObject gets deleted. I'm new to coding, so a basic solution would be better :) .
Here's my coding:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyHealthManager : MonoBehaviour {

    public int enemyHealth;
    public GameObject deathEffect;
    public int pointsOnDeath;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update ()
    {
        if (enemyHealth <= 0)
        {
            Instantiate (deathEffect, transform.position, transform.rotation);
            ScoreManager.AddPoints (pointsOnDeath);
            Destroy (gameObject);

        }
    }

    public void giveDamage(int damageToGive)
    {
        enemyHealth -= damageToGive;
    }
}

A: You can add a function called PlayAnimationAndDestroy() as a void and inside it put the Destroy (this.gameObject, 2f) and then animator.Play("deathAnim");
In the Destroy the number after the comma is the time Unity will wait to destroy the object so you need to check the duration of your animation in the timeline and put that duration in the Destroy ().
Another way to do this is to press the record button inside the animation at the end of it and change a public variable. In the script you will put a simple if() and If that variable has changed you destroy the object.
The third way is to use animation events (https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html) but for your usage the first two options are easier :)

A: Welcome to Unity! Using an AnimatorController in your project and corresponding Animator components on your GameObject that you want to die is going to be your friend here as well.
You can check out a great tutorial by Unity about Animator Controllers here, but basically, it's a state machine. Based on what state your object is in, you can control which game object animations are active and you can set triggers in your game logic to trigger a transition to another state.
This is great for cases like triggering death animations.
In your case, you'd want one state for idle, and one state for death. You'd have a connection between your death and idle state.
You'd set a trigger named die. You'd make it so that the state idle only moves to state death when your die trigger is triggered in the game logic.
So, step 1:
You'd create a new AnimatorController Scriptable Object from the Editor, and then edit it in the Animator window. Make your desired state machine with the desired animations and that ScriptableObject will be saved in a project folder.
Step 2: Add an Animator component on your GameObject that you want to affect. It has an AnimatorController component - add your newly created controller here.
Step 3: In your game logic script, you'd have a reference to that Animator component:
...
public int enemyHealth;
public GameObject deathEffect;
public int pointsOnDeath;
public Animator animComponent;
...

Then when you hit your condition, you'd do something like this:
if (enemyHealth < 0){
    animComponent.SetTrigger("die");
}

Then your AnimatorController will move from your previous state to death, and your animation that you set will play.
Best of luck.


text:
Q: Highest power contained in the expression. Lets say we have a polynomial $N$ which has been expressed in $p$ where $p$ is a prime and all the coefficients in the polynomial are less than $p$. We are asked to prove, that the highest power of $p$ contained in $N!$ would be $(N-s) \over (p-1)$ where $s$ is the sum of all the coefficients.
I tried to do the question by making up the expression of $N$
$$N=a_0+a_1p^1+a_2p^2.......+a_np^n$$
where $a_0+a_1+a_2+.........+a_n=s$
Now the highest power of p contained would be
$$[N/p]+[N/p^2]+[N/p^3]+......+[N/p^n]$$
$$[N/p]=a_0/p+a_1+a_2p+.....+a_np^{n-1}$$
$$[N/p^2]=a_0/p^2+a_1/p+a_2+.....+a_np^{n-2}$$
$$..$$$$..$$$$..$$$$[N/p^n]=a_0/p^n+a_1/p^{n-1}+a_2p^{n-2}+.....+a_n$$
adding them all would give
$[N/p]+[N/p^2]+[N/p^3]+......+[N/p^n]=(a_1+a_2+a_3....a_n)+{1/p}(a_0+a_1+a_2+a_3....a_{n-1})+{1/p^2}(a_0+a_1+a_2+a_3....a_{n-2})....+1/p^n(a_0)+p(a_2+a_3....+a_n)+p^2(a_3+a_4....+a_n)+....+p^n(a_n)$
Though the things can be summed up to a large extent by the use of GP and writing $a_0+a_1+a_2+a_3....a_n=s$   but the expression is becoming pretty much complicated and I am unable to extract as the expression has become so much complicated.
Please provide the solution/hint(more preferable) to the question using only basic number theory expressions as it was in the first exercise of my book and the author wants me to solve it the simple way only.

A: The integer parts do not include fractions, so for example
$$\lfloor N/p\rfloor=a_1+a_2p+...+a_np^{n-1}\\ \lfloor N/p^2\rfloor=a_2+a_3p+...+a_np^{n-2}$$
When you add them up, try collecting the $a_i$ instead of $p$.  For example, $a_3$ is multiplied by $p^2+p+1$.
Multiply the full sum by $p-1$ and try to make the result equal $N-s$.


text:
Q: How to scroll long text in TextView indefinitely I want to animate my TextView indefinitely when text is too long. I found some solution but it is reseting after 2 seconds back to start of the text even if some text is still needed to scroll. I need animation infinite and it should scroll whole text and at the end start of the text will appear.
Same as those information boards on train stations.
This is my animation right now:
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromXDelta="100"
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="infinite"
    android:toXDelta="-100" />

There is repeat count but I dont want to repeat animation and reset to initial position but animate it all the time.

A: You don't need an animation, a simple Marquee TextView would do:
<TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:text="Your Sample text here" />

Make sure you have the marquee mode set (in the ellipsize attribute as above) and the maximum lines set to 1 for it to work. You can choose to repeat it indefinitely, or a specific amount of times, by replacing the marquee_forever with an integer.

A: If you need to stop repeat mode nad set view at the initial point then you can set count as -1.
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromXDelta="100"
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="-1"
    android:toXDelta="-100" />

You can set repeatmode as Animation.REVERSE if you need.
And need to do dynamically then can use following way.
   mScanner.setVisibility(View.VISIBLE);
   mAnimation = new TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 1.0f);
   mAnimation.setDuration(10000);
   mAnimation.setRepeatCount(-1);
   mAnimation.setRepeatMode(Animation.REVERSE);
   mAnimation.setInterpolator(new LinearInterpolator());
   mScanner.setAnimation(mAnimation);

A: You can try this:
<TextView
       android:id="@+id/rv_item_tv_address"
       android:layout_width="0dp"
       android:layout_height="wrap_content"
       android:layout_margin="10dp"
       android:ellipsize="marquee"
       android:focusable="true"
       android:focusableInTouchMode="true"
       android:gravity="center"
       android:marqueeRepeatLimit="marquee_forever"
       android:scrollHorizontally="true"
       android:singleLine="true"
       android:text="address"
       android:textColor="@color/colorPrimary"
       android:textSize="20sp"
      />


text:
Q: WhatsApp using huge space on my Mac SSD My parents gave me a MacBook for Christmas with a 256GB SSD and a few days ago I notice I only have 40GB left on the SSD.
I tried researching this and according to this question (How can I figure out what's slowly eating my HD space?) I download DaisyDisk to discover why so much of my space was gone after only 4 months. This showed me that com.apple.bird was taking up 89GB!
So I researched this also and an answer to this question (What is com.apple.bird? Why does it grow so big?) suggested using a script to tell me what apps are using this 89GB. I actually got the script to work (pat on back for me!) and this tells me that WhatsApp is the problem.
Now I'm freaking out because my friends and I all use WhatsApp to talk about school, parties, life and I don't know what to do. I use WhatsApp on my iPhone 5c mainly, but the answers to the question about com.apple.bird are really scary to me because it's not clear if i will lose everything if I delete what's in com.apple.bird? But, if I don't delete it, I'll run out of space soon!
How do I fix this?

A: Although not addressing your bird issue directly, whenever these things happens to me I have to assume it is going to happen again in the future. That's why after WhatsApp and iMessages grew too large on my phone I decided to migrate my conversations to the Telegram service, which is basically the same thing but cloud based. That means people can send me 100's of MB of video and the size of the app remains the same — WhatsApp OTOH just grows with every video I receive.
Granted, your problem might just have been a caching bug and you're otherwise fine with the app size, but I hopefully never have to do housecleaning again and couldn't be happier with the switch.
Currently on my phone:

*

*iMessage 512 MB

*WhatsApp 189 MB

*Facebook Messenger (clean install -- never used) 165 MB

*Telegram 37 MB

Not affiliated with Telegram in any way

A: If you don't already, I want to suggest in the strongest terms possible that you have a Time Machine backup of your data. A portable 1TB hard drive is not expensive and you can plug it in and Time Machine will prompt you if you want to use it for backups. I would do that before proceeding with any answers provided (mine included).
As for that huge 89GB of data, this is actually safe to remove. However, please don't do this manually. Instead, follow these steps:

*

*On your iPhone ensure you have iCloud activated

*Make sure your MacBook is connected to the internet

*On your MacBook, go to Apple > System Preferences

*Click on iCloud

*At the top where you have the iCloud Drive checkbox ticked, untick it

*A somewhat scary message will appear - click on the Delete from Mac button. Don't worry, your documents will still be on iCloud (and that's another reason why we made sure iCloud was activated on your iPhone at Step 1)

*Exit System Preferences

*Within about 5 minutes most of that 89GB in com.apple.bird will be freed up

*Once you're satisfied that you've freed up all that space, repeat Steps 3 & 4

*At the top you can now tick the iCloud Drive checkbox again

*Exit System Preferences

Let me know if my steps aren't clear or if you have any problems.
Remember: - Make sure you regularly backup your MacBook.


text:
Q: how to send user id in secure way using get method I am trying to secure my user id. I have to page user.php and user_account.php. I am sending user to user_account.php by a anchor tag.
In user_account.php page it is showing this plain user_id(as like 25, 26,23). It is potential security threat for my application. I have to do some operation based on the user_id that is sending form user.php page.
I get it that first I have to encrypt it and then have to decypt it.
here is my code:
echo ''.$user_name.'';

I am sending it from my user.php page. and user_account.php page just get it by get method.
But how can I send it secure way and prevent user from manipulate it
.Any king of help will be appreciated

A: The best way to secure against misuse of the user id would be to Authenticate the user and check whether the authenticated user has permission to access that user.
Aside
Any other "encryption" method as suggested by other answers is reversible once the hashing algorithm is known. You could add a salt among other things, but I strongly suggest against rolling your own security, especially in this very specific case. You want a method generalized enough be reusable in other areas of your application that you want to be secure, otherwise you end up with spaghetti code.
Also, this almost goes without mentioning, but you should also be using SSL.

A: Just use the base64_encode() and base64_decode() methods to encrypt and decrypt your id like below:
user.php
echo ''.$user_name.''; // encrypt id

user_account.php
$single_id = base64_decode($_GET['id']); // get id and decrypt it.

A: You can use crypt() here.

encrypt your $user_id

<?php
// Get the hash of $user_id
$single_id = crypt($user_id);
echo ''.$user_name.'';
?>

now decrypt it as below

if (hash_equals($single_id, crypt($user_id, $single_id))) {
   echo "User Id matched";
}


text:
Q: Nativescript - onesignal failed to find module: nativescript-onesignal relative to app/tns_modules/ I really don´t know where to search anymore, i see a lot of related problems but i seem to resolve one problem and then another one appears. The thing is, i´m using onesignal(with nativescript sdk) to send push notifications, and on ios everything works well, but then when i try to run locally on my android, many problems appear:
First problem was i was getting a maven { url "https://plugins.gradle.org/m2/" } so i followed the instructions here and i mannage to get rid of that problem.Also i think is important to say that i´m using sidekick and from here i installed the onesignal plugin which points to here but in those instructions(in the previous link i gave) points to another plugin...ok...no problem, i followed the rest of the instructions and now my Second problem is that the app IS installed on the run, but it breaks and shows the error that you see on the log below:
System.err: Error: com.tns.NativeScriptException: Failed to find module: "nativescript-onesignal", relative to: app/tns_modules/
System.err:     com.tns.Module.resolvePathHelper(Module.java:146)
System.err:     com.tns.Module.resolvePath(Module.java:55)
System.err:     com.tns.Runtime.runModule(Native Method)
System.err:     com.tns.Runtime.runModule(Runtime.java:553)
System.err:     com.tns.Runtime.run(Runtime.java:545)
System.err:     com.tns.NativeScriptApplication.onCreate(NativeScriptApplication.java:21)
System.err:     android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1017)
System.err:     android.app.ActivityThread.handleBindApplication(ActivityThread.java:4864)
System.err:     android.app.ActivityThread.access$1500(ActivityThread.java:178)
System.err:     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
System.err:     android.os.Handler.dispatchMessage(Handler.java:111)
System.err:     android.os.Looper.loop(Looper.java:194)
System.err:     android.app.ActivityThread.main(ActivityThread.java:5643)
System.err:     java.lang.reflect.Method.invoke(Native Method)
System.err:     java.lang.reflect.Method.invoke(Method.java:372)
System.err:     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
System.err:     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
System.err: File: "<unknown>, line: 1, column: 265
System.err: StackTrace:
System.err:     Frame: function:'require', file:'', line: 1, column: 266
System.err:     Frame: function:'', file:'file:///data/data/pt.wemakeapps.brleads/files/app/app.js', line: 8, column: 22
System.err:     Frame: function:'require', file:'', line: 1, column: 266
System.err: Error: com.tns.NativeScriptException: Failed to find module: "nativescript-onesignal", relative to: app/tns_modules/
System.err:     com.tns.Module.resolvePathHelper(Module.java:146)
System.err:     com.tns.Module.resolvePath(Module.java:55)
System.err:     com.tns.Runtime.runModule(Native Method)
System.err:     com.tns.Runtime.runModule(Runtime.java:553)
System.err:     com.tns.Runtime.run(Runtime.java:545)
System.err:     com.tns.NativeScriptApplication.onCreate(NativeScriptApplication.java:21)
System.err:     android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1017)
System.err:     android.app.ActivityThread.handleBindApplication(ActivityThread.java:4864)
System.err:     android.app.ActivityThread.access$1500(ActivityThread.java:178)
System.err:     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
System.err:     android.os.Handler.dispatchMessage(Handler.java:111)
System.err:     android.os.Looper.loop(Looper.java:194)
System.err:     android.app.ActivityThread.main(ActivityThread.java:5643)
System.err:     java.lang.reflect.Method.invoke(Native Method)
System.err:     java.lang.reflect.Method.invoke(Method.java:372)
System.err:     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
System.err:     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
System.err: File: "<unknown>, line: 1, column: 265
System.err: StackTrace:
System.err:     Frame: function:'require', file:'', line: 1, column: 266
System.err:     Frame: function:'', file:'file:///data/data/pt.wemakeapps.brleads/files/app/app.js', line: 8, column: 22
System.err:     Frame: function:'require', file:'', line: 1, column: 266
System.err:     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4867)
System.err:     at android.app.ActivityThread.access$1500(ActivityThread.java:178)
System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
System.err:     at android.os.Handler.dispatchMessage(Handler.java:111)
System.err:     at android.os.Looper.loop(Looper.java:194)
System.err:     at android.app.ActivityThread.main(ActivityThread.java:5643)
System.err:     at java.lang.reflect.Method.invoke(Native Method)
System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
System.err: Caused by: com.tns.NativeScriptException:
System.err: Error calling module function
System.err: Error: com.tns.NativeScriptException: Failed to find module: "nativescript-onesignal", relative to: app/tns_modules/
System.err:     com.tns.Module.resolvePathHelper(Module.java:146)
System.err:     com.tns.Module.resolvePath(Module.java:55)
System.err:     com.tns.Runtime.runModule(Native Method)
System.err:     com.tns.Runtime.runModule(Runtime.java:553)
System.err:     com.tns.Runtime.run(Runtime.java:545)
System.err:     com.tns.NativeScriptApplication.onCreate(NativeScriptApplication.java:21)
System.err:     android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1017)
System.err:     android.app.ActivityThread.handleBindApplication(ActivityThread.java:4864)
System.err:     android.app.ActivityThread.access$1500(ActivityThread.java:178)
System.err:     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
System.err:     android.os.Handler.dispatchMessage(Handler.java:111)
System.err:     android.os.Looper.loop(Looper.java:194)
System.err:     android.app.ActivityThread.main(ActivityThread.java:5643)
System.err:     java.lang.reflect.Method.invoke(Native Method)
System.err:     java.lang.reflect.Method.invoke(Method.java:372)
System.err:     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
System.err:     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
System.err: File: "<unknown>, line: 1, column: 265
System.err: StackTrace:
System.err:     Frame: function:'require', file:'', line: 1, column: 266
System.err:     Frame: function:'', file:'file:///data/data/pt.wemakeapps.brleads/files/app/app.js', line: 8, column: 22
System.err:     Frame: function:'require', file:'', line: 1, column: 266
System.err: Error: com.tns.NativeScriptException: Failed to find module: "nativescript-onesignal", relative to: app/tns_modules/
System.err:     com.tns.Module.resolvePathHelper(Module.java:146)
System.err:     com.tns.Module.resolvePath(Module.java:55)
System.err:     com.tns.Runtime.runModule(Native Method)
System.err:     com.tns.Runtime.runModule(Runtime.java:553)
System.err:     com.tns.Runtime.run(Runtime.java:545)
System.err:     com.tns.NativeScriptApplication.onCreate(NativeScriptApplication.java:21)
System.err:     android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1017)
System.err:     android.app.ActivityThread.handleBindApplication(ActivityThread.java:4864)
System.err:     android.app.ActivityThread.access$1500(ActivityThread.java:178)
System.err:     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1531)
System.err:     android.os.Handler.dispatchMessage(Handler.java:111)
System.err:     android.os.Looper.loop(Looper.java:194)
System.err:     android.app.ActivityThread.main(ActivityThread.java:5643)
System.err:     java.lang.reflect.Method.invoke(Native Method)
System.err:     java.lang.reflect.Method.invoke(Method.java:372)
System.err:     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
System.err:     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
System.err: File: "<unknown>, line: 1, column: 265
System.err: StackTrace:
System.err:     Frame: function:'require', file:'', line: 1, column: 266
System.err:     Frame: function:'', file:'file:///data/data/pt.wemakeapps.brleads/files/app/app.js', line: 8, column: 22
System.err:     Frame: function:'require', file:'', line: 1, column: 266
System.err:     at com.tns.Runtime.runModule(Native Method)
System.err:     at com.tns.Runtime.runModule(Runtime.java:553)
System.err:     at com.tns.Runtime.run(Runtime.java:545)
System.err:     at com.tns.NativeScriptApplication.onCreate(NativeScriptApplication.java:21)
System.err:     at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1017)
System.err:     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4864)

So, what is the problem? any thoughts?
Thanks for your time
Regards


text:
Q: $(f \star f \star f) (x) $ at $x = 0$ $$g(x) = (f \star f ) (x)$$ and $$q(x) =  (f \star f  \star f) (x)$$ where $\star$ denotes convolution.
I can write $$g(x) = \int\limits_{-\infty}^{\infty}f(\tau)f(\tau - x) d \tau$$
Therefore $$g(0) = \int\limits_{-\infty}^{\infty}f(x)f(x) dx$$
Is there a similar simplification for $q(0)$?
I started with $$q(0) = \int\limits_{-\infty}^{\infty}f(\lambda) \left(\int\limits_{-\infty}^{\infty} f(\tau)f(\tau - \lambda) d \tau \right) d \lambda$$
Can this be further simplified? Is there a possibility of expressing $q(0)$ with an integral involving one variable (like $g(0)$)?

A: Firstly, your formulas for $g(x)$ and $q(x)$ are incorrect, which are giving you the wrong impression. It's crucial for convolutions that $\tau$ goes up and $-\tau$ goes down as the integration variable increases. We have: $g(x)=\displaystyle{\int_{-\infty}^{\infty}}f(\tau)f(x-\tau)\,\mathrm{d}\tau$ and similarly for $q$.  Therefore, the tidy formula for $g(0)$ is actually $\displaystyle{\int_{-\infty}^{\infty}}f(x)f(-x)\,\mathrm{d}x$, which only equals your expression if $f$ is even.

For $(f\star f\star f)(0)$ you would take a formula for triple convolution (just imagine that $\mathbb{T}$ at that link is replaced with $(-\infty,\infty)$) and substitute in $0$.
We get formulas like $\displaystyle{\int_{-\infty}^{\infty}}f(y)\displaystyle{\int_{-\infty}^{\infty}}f(x)f(-x-y)\,\mathrm{d}x\,\mathrm{d}y$ and $\displaystyle{\int_{-\infty}^{\infty}}f(-y)\displaystyle{\int_{-\infty}^{\infty}}f(x)f(y-x)\,\mathrm{d}x\,\mathrm{d}y$
You can move the outer $f(y)$ or $f(-y)$ inside the inner integral if you like, but unless $f$ is even or has some other special property, you're not going to get something simpler.


text:
Q: Why X509Certificate2 gets Internal Error only if the password is correct I'm trying to understanding why in .NET, calling the constructor System.Security.Cryptography.X509Certificates.X509Certificate2() fails with an "internal error" when a file name and matching password are passed.  This happens on a Windows 2008 R2 server.  On a different machine, running Windows 7, the call works properly using the same file name and password (actually, I tried with two different pairs of files and passwords and got the same results).  I'm hoping that there's just some setting that must be enabled (or disabled) on the Windows 2008 R2 server for this command to work.  (The server has much more stringent security, so maybe it's blocking something?)  But to better understand the problem, I guess I need to get a better sense of what .X509Certificate2() is actually doing.
For starters, the following two commands work fine on both machines:
    var x = new X509Certificate2();
    var y = new X509Certificate2(fullFilePath);

However, any of the overloads that take a password will fail on the Windows 2008 R2 server if the password is correct, but not on the Windows 7 machine.  (Both are 64-bit.)  For example:
    var z = new X509Certificate2(fullFilePath, password);

If I pass an incorrect or blank password (on either machine), then I get "The specified network password is not correct."  However, if the password is correct, then the Windows 2008 R2 server says "An internal error occurred."
This leads me to believe that somewhere in the X509Certificate2 code, if the password is found to match, then another action is taken, and that's the one that's failing.
I did find some information on the source code through a Google search that brought me here:
http://www.dotnetframework.org/default.aspx/4@0/4@0/DEVDIV_TFS/Dev10/Releases/RTMRel/ndp/fx/src/security/system/security/cryptography/x509/X509Certificate2@cs/1305376/X509Certificate2@cs
... but I'm still having some difficulty understanding what's going on.  Apparently, no matter what parameters are passed, they're dealt with somehow in this line:
m_safeCertContext = CAPI.CertDuplicateCertificateContext(this.Handle);
...but I haven't been able to find the source code for that yet.
What I'm hoping, actually, is to find that maybe someone knows that "oh yes, on Windows 2008 servers, you have to make sure that xyz is enabled for X509Certificate2() to work, and all you have to do is..." or that there must be something else on the machine besides that file being there in the specified place for the constructor to work.
My end goal is to have program working on the server, in the same way as it works on the other machine.  However, just having some information on the logic of exactly what happens when I make this call (and what gets executed after it finds that the password matches) would help immensely.
Any insights are appreciated!

A: Try
var certificate = new X509Certificate2(fileName, password, X509KeyStorageFlags.MachineKeySet);


text:
Q: How can I add multiple of lines text (a paragraph) to an svg? I want to add multiple lines of text to an svg, which would be contained within the svg (does not overflow). How can I do that?
I knew that the text tag is used in svg, but I discovered that it's single lined. Then, when I give it textLength (so that it would contained in specific svg), its words overlap with each other. How can I put multiple lines of text which would adjust in svg tag? The code I tried is below:

<svg width="200" height="60" style="border: 1px solid black;">
  <text x="10" y="30" textLength="180" style="font-size: 30px;">The paragraph here</text>
</svg>

A: It doesn't work. SVG has no mechanism for breaking lines.
That said, you would be able to encapsulate a html
 tag as a foreignObject:
<svg xmlns="http://www.w3.org/2000/svg"
     width="21cm" height="29.7cm" style="border:1px solid black;">
  <foreignObject x="6.4cm" y="3.6cm" width="10cm" height="10cm">

The paragraph here

  </foreignObject>
</svg>

Please note that the namespace declarations must be given, and you need to write valid XHML for this to work.
In addition, foreignObject is part of the SVG context, so a width and height need to be set, otherwise it will have no inherent size.


text:
Q: Why is the number of possible subsequences $2^n$? If anyone here is familiar with the Lowest Common Subsequence problem, they probably know that the number of posibble subsequences in a sequence is $2^n$; $n$ being the length of the sequence.
Another way of phrasing the statement is: given the sample space $\{a,b,c,d\}$, there are $2^4 = 16$ possible events (each event being defined as a subset of the whole sample space).
I know it sounds a fairly basic question, but can anybody please explain why is this so?

A: Let us take as an example a somewhat larger problem, with a sample space of $6$ rather than your $4$.  Bhaskara, more than $800$ years ago, posed and solved a similar problem.  There are $6$ basic flavours, sweet, sour, salty, bitter, pungent, and astringent.  How many different combinations of flavours are possible?
Let us imagine that bowls of these flavouring ingredients are lined up in front of a cook. Call the bowls A, B, C, D, E, and F.
The cook wants to create a combination of flavours by taking a tablespoon of flavouring ingredient out of some (possibly all, possibly none) of the bowls, and not using the remaining flavouring ingredients.  So (s)he stops in front of each bowl, going from left to right, and makes a decision.
Let us summarize what the cook chooses to do by using a $6$-letter word over the alphabet that consists of the "letters" $0$ and $1$.
For example, $011001$ will mean that the cook did not use ingredient A, used B and C, did not use D and E, but used F.
It should be clear that there are exactly as many ways to choose a combination of flavourings as there are "words" of length $6$ over the alphabet $\{0,1\}$. You may already know that there are $2^6$ such words. But let us look at things from the viewpoint of the cook.
The cook stops briefly in front of bowl A. The cook has $2$ choices as to what to do: use A or not use A.  For each such choice, the cook has $2$ choices about whether to use flavour B.  For every choice about what to do with A and B, the cook has $2$ choices about what to do about C. And so on.
Thus in total the cook has
$$2\times 2\times 2\times 2  \times 2 \times 2$$
ways of deciding about the flavourings.
This is $2^6$, or $64$.  Actually, Bhaskara got an answer of $63$, for he did not count the possibility of saying no to each flavouring, that is, of choosing the empty set of flavourings.  I guess he had not heard about English cooking.

A: If the order of the elements in each subsequence does not matter, then every subsequence is an element of the powerset of the given sequence.
In your example, the powerset of your sequence A contains
$\{\}, \{a\}, \{b\}, \{c\}, \{d\}, \{a, b\}, \{a, c\}, \{a, d\}, \{b, c\}, \{b, d\}, \{c, d\}, \{a, b, c\}, \{a, b, d\},$
$\{a, c, d\}, \{b, c, d\}, \{a, b, c, d\}$
each one being considered as a subsequence.
Consider then the cardinality of the powerset:
if a set A contains n elements, then the powerset of A contains $2^n$ elements.

A: Either include A or exclude A.  2 possibilities.
Either include B or exclude B.  2 possibilities.
Either include C or exclude C.  2 possibilities.
Either include D or exclude D.  2 possibilities.
So the answer is $2\times2\times2\times2$.

A: The proof can be given by induction. For set of n elements, the number of subsets are $2^n$. For the set of n + 1 elements, you can take the previous $2^n$ elements and add the (n + 1)th element in each of these sets. So now you have $2^n$ (original subsets) + $2^n$ (new subsets). It is simple to see the result now. I haven't mentioned base case as it is elementary.

A: Another way of thinking about this problem:
For any given sub-sequence a specific element can either be included or excluded.  This means you have 2 possibilities for each element and a total of n-elements.  Thus there are $2^n$ possible ways to generate a sub-sequence.

Another possible way to wrap your head around the concept.  Think of every sub-sequence as containing $n$ blank spaces, each corresponding to one of the elements of your original sequence.  You can then fill each of these blanks with either a 1 to denote the inclusion of that element or a 0 to denote the exclusion of that element.  That gives 2 possibilities for each blank.  There are n blanks, thus $2^n$ possible sub sequences.

A: Its not necessay that evey number has total subsequence is equal to 2^n.
For e.g: number 12345 has following subsequence equal to 25 only. 2^n are number of subsets...
--> 1 2 3 4 5
--> 12 13 14 15 23 24 25 34 35 45
--> 123 124 125 234 235 345
--> 1234 1235 1245 1345 2345
--> 12345


text:
Q: How to pass non-string values into a prepared statement in PHP I have a few lines of code below to execute a prepared statement with PHP on my PostgreSQL database. However, it fails because some values are automatically converted to string while in my case, the uid and edu_year should be integers:
$query = "INSERT INTO education(uid, year, diploma, school, major)
   VALUES ($1, $2, $3, $4, $5)";
pg_prepare($conn, "my_query", $query);
pg_execute($conn, "my_query", array($_SESSION['uid'], $_POST['edu_year'][$i],
   $_POST['edu_diploma'][$i], $_POST['edu_school'][$i], $_POST['edu_major'][$i]));

Does anyone know how to make this work, or is there another, more preferred way of achieving this?

A: You just need to case them into integer:
pg_execute($conn, "my_query", array((int)$_SESSION['uid'], (int)$_POST['edu_year'][$i], $_POST['edu_diploma'][$i], $_POST['edu_school'][$i], $_POST['edu_major'][$i]));


text:
Q: Angular $resource not passing parameter to Express service I have an Angular application that needs to be able to get construct data from a MongoDB collection.   I am using the $resource service in the flConstruct to request data from the server.  The "query" call returns all data and appears to be working fine.  When I try to retrieve data for just one of the constructs using the 'get' no data is returned.
I have printed to the console to look at what is getting to the service and I do not see the parameter being available to the findOne function.  Below is the output to the console
Get - constructs.getConstructById
constructData.id undefined
req.params._id undefined
req.query._id undefined
No Error - Construct Data Retrieved
Get - constructs.getConstructs (Id) - No Error
Returned - construct null
Get - constructs.getConstructs (Id) - Sending Back question
Get - constructs.getConstructs (Id) - Sending Back neither error nor question

//Angular service named, flConstruct
angular.module('app').factory('flConstruct',function($resource){
var ConstructResource = $resource('/api/constructs/:id', {id: "@id"}, {
    get: { method: 'GET', url: '/api/constructs/byId/:id', params: {id: "@id"}},
    query: { method: 'GET' , url: '/api/constructs', isArray: true },
    create: { method: 'POST'},
    update: { method: 'PUT' },
    delete: { method: 'DELETE', params: {id: '@id'}}
});

return ConstructResource;
});

//Express config file named, routes.js
var constructs = require('../controllers/constructs'),

module.exports = function(app){

app.get('/api/constructs', constructs.getConstructs);
app.get('/api/constructs/byId', constructs.getConstructById);

app.post('/api/constructs', constructs.createConstruct);
app.put('/api/constructs', constructs.updateConstruct);
app.delete('/api/constructs/:id', constructs.deleteConstruct);
});
}

// Express controller named, construct.js
var Construct = require('mongoose').model('Construct');

exports.getConstructs = function(req,res){
var constructData = req.body;
console.log("Get - constructs.getConstructs");
console.log("constructData.id " + constructData.id);
console.log("constructData " + constructData);
console.log("req.params.id " + req.params.id);
console.log("req.query.id " + req.query.id);
Construct.find({}).exec(function(err,collection){
    if (err){
        console.log("Error - No Construct Retrieved");
    }else
    {
        console.log("No Error - Construct Data Retrieved");
    }
    //console.log(collection);
    res.send(collection);
})
};

exports.getConstructById = function(req,res) {
console.log("Get - constructs.getConstructById")
var constructData = req.body;
console.log("constructData.id " + constructData.constructId);;
console.log("req.params._id " + req.params._id)
console.log("req.query._id " + req.query._id)
Construct.findOne({_id:req.params.id}).exec(function(err,construct){
if (err){
    console.log("Error - No Construct Retrieved");
    console.log("Get - constructs.getConstructs (Id) - Error");
    res.send(null);
}else
{
    console.log("No Error - Construct Data Retrieved");
    console.log("Get - constructs.getConstructs (Id) - No Error");
    //console.log("Returned - construct._id " + construct._id)
    //console.log("Returned - construct.id " + construct.id)
    console.log("Returned - construct " + construct)
    console.log("Get - constructs.getConstructs (Id) - Sending Back question");
    res.send(construct);
}
console.log("Get - constructs.getConstructs (Id) - Sending Back neither error nor     question");
})

};

A: I found my mistake. It is all within the Angular code.  The call to the get that is made in the flCachedConstruct.js did not properly define the parameter to be passed. I needed to include the parameter name, "id" as well as the parameter value, constructID. The "id" in this function call matches what I called the parameter in flConstruct.js.
flConstruct.get({id: constructId }, function(data) {


text:
Q: Is there any way to append a string value to key of a hash in Redis? Redis provided solution to append string value to a key.

APPEND mykey "Hello"

but not find any solution to append string value to a key of hash.

A: There is RENAME command.
RENAME oldkey newkey

To clarify, if you want to append World to an existing key Hello,
RENAME Hello HelloWorld