text:
Q: Draw transparent bitmap on backgound I want to draw transparent bitmaps on a background in a game. However, the bitmap is not transparent, it still has white color in the background. Here is my code
inner class Canvass(context: Context) : View(context) {
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val frame_paint: Paint = Paint()
        frame_paint.style = Paint.Style.FILL
        frame_paint.isAntiAlias = true

        val framegame = BitmapFactory.decodeResource (resources, R.drawable.frame)
        canvas.drawBitmap (framegame, 0f, 0f, frame_paint)

        canvas.drawPath(mPath, mPaint)

        val tennis_paint: Paint = Paint()
        tennis_paint.style = Paint.Style.FILL
        tennis_paint.color = Color.TRANSPARENT
        tennis_paint.isAntiAlias = true

        val tennis = BitmapFactory.decodeResource (resources, R.drawable.tennis_ball)
        canvas.drawBitmap (tennis, 50f, 200f, tennis_paint)
    }
}

A: I found this code, it works for me.
        val tennis_paint: Paint = Paint()
        tennis_paint.style = Paint.Style.FILL
        tennis_paint.isAntiAlias = true

        val tennis = BitmapFactory.decodeResource (resources, R.drawable.tennis_ball)
        var bitmap = transparent_bitmap(tennis)
        canvas.drawBitmap (bitmap, 50f, 300f, tennis_paint)

 fun transparent_bitmap(bmp:Bitmap):Bitmap{

        var bitmap: Bitmap = Bitmap.createBitmap(
            bmp.width,
            bmp.height,
            Bitmap.Config.ARGB_8888
        )

        bitmap.setHasAlpha(true)

        for (x in 1..bmp.width-1){
            for (y in 1..bmp.height-1){
                var pixel = bmp.getPixel(x,y)
                val redValue = Color.red(pixel)
                val blueValue = Color.blue(pixel)
                val greenValue = Color.green(pixel)

                if ((redValue==255)and(blueValue==255)and(greenValue==255)){
                    bitmap.setPixel(x,y,Color.argb(1,0,0,0))
                }else {
                    bitmap.setPixel(x,y,Color.rgb(redValue,greenValue,blueValue))
                }
            }
        }

        return bitmap
    }


text:
Q: How to access Log4Net after adding it to Dependency Injection This is my first time working with Microsoft.Extensions.Logging.Log4Net.AspNetCore.
I have a WPF application where I add the Log4Net provider within the CreateDefaultBuilder in App method of App.xaml.cs. Immediately after, I want to write to the log file using LogInformation saying "Starting Application". From what I can tell, it does not seem like I can do this because of the way it has been added to the Dependency Injection container. I must either call a method that accesses the DI container in the parameter list or add Log4Net to the ServiceProvider and then retrieve the service that way. But, that does not seem right because I will effectively have Log4Net added to DI twice.
Is there a way to immediately access the DI container after configuring Log4Net so I can write to the log file?
Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
.ConfigureAppConfiguration((context, appBuilder) =>
{
   // Do some stuff here
}).ConfigureLogging(logBuilder =>
{
   logBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
   logBuilder.AddLog4Net("log4net.config");
})
.ConfigureServices((context, services) =>
{
   Configuration = context.Configuration;

   ConfigureServices(Configuration, services);
})
.Build();

ServiceProvider = Host.Services;

// How to access Log4Net here?
_ISomeLogger.LogInformation("Starting Application");

Update
I am using the following example: https://www.thecodebuzz.com/logging-using-log4net-net-core-console-application/

A: The solution is to access the Log4Net from the ServiceProvider right after building it:
logger = (ILogger<Program>)ServiceProvider.GetService(typeof(ILogger<Program>));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do you need crt2.o in C++? Programm Hello World (hello.s)
    .data
LC0:
    .ascii "Hello, World!\0"
    .text
    .globl  _main
_main:
    pushl   %ebp
    movl    %esp, %ebp
    andl    $-16, %esp
    subl    $16, %esp
    movl    $LC0, (%esp)
    call    _puts
    xorl    %eax, %eax
    leave
    ret

1 compilation method
as.exe hello.s
ld -s a.out -LC:\gcc\lib -lmsvcrt -o hello.exe(2kb)

2 compilation method(standart)
as.exe hello.s
gcc -s a.out -o hello.exe(12kb)

I found that the increase in the size of hello.exe is associated with the attachment of the crt2.o file. What specific function does it perform?


text:
Q: Generate syntax-colored, hyperlinked source code from Haskell or Objective-C Are there any packages that can take a directory full of source code (Objective-C and Haskell are the ones that interest me) and generate syntax-colored HTML from it where function names are links to their source code?

A: For haskell you can take a look at Haddock:
http://www.haskell.org/haddock/


text:
Q: Replace values in a pandas series via dictionary efficiently How to replace values in a Pandas series s via a dictionary d has been asked and re-asked many times.
The recommended method (1, 2, 3, 4) is to either use s.replace(d) or, occasionally, use s.map(d) if all your series values are found in the dictionary keys.
However, performance using s.replace is often unreasonably slow, often 5-10x slower than a simple list comprehension.
The alternative, s.map(d) has good performance, but is only recommended when all keys are found in the dictionary.
Why is s.replace so slow and how can performance be improved?
import pandas as pd, numpy as np

df = pd.DataFrame({'A': np.random.randint(0, 1000, 1000000)})
lst = df['A'].values.tolist()

##### TEST 1 #####

d = {i: i+1 for i in range(1000)}

%timeit df['A'].replace(d)                          # 1.98s
%timeit [d[i] for i in lst]                         # 134ms

##### TEST 2 #####

d = {i: i+1 for i in range(10)}

%timeit df['A'].replace(d)                          # 20.1ms
%timeit [d.get(i, i) for i in lst]                  # 243ms

Note: This question is not marked as a duplicate because it is looking for specific advice on when to use different methods given different datasets. This is explicit in the answer and is an aspect not usually addressed in other questions.

A: One trivial solution is to choose a method dependent on an estimate of how completely values are covered by dictionary keys.
General case

*

*Use df['A'].map(d) if all values mapped; or

*Use df['A'].map(d).fillna(df['A']).astype(int) if >5% values mapped.

Few, e.g. < 5%, values in d

*

*Use df['A'].replace(d)
The "crossover point" of ~5% is specific to Benchmarking below.
Interestingly, a simple list comprehension generally underperforms map in either scenario.
Benchmarking
import pandas as pd, numpy as np

df = pd.DataFrame({'A': np.random.randint(0, 1000, 1000000)})
lst = df['A'].values.tolist()

##### TEST 1 - Full Map #####

d = {i: i+1 for i in range(1000)}

%timeit df['A'].replace(d)                          # 1.98s
%timeit df['A'].map(d)                              # 84.3ms
%timeit [d[i] for i in lst]                         # 134ms

##### TEST 2 - Partial Map #####

d = {i: i+1 for i in range(10)}

%timeit df['A'].replace(d)                          # 20.1ms
%timeit df['A'].map(d).fillna(df['A']).astype(int)  # 111ms
%timeit [d.get(i, i) for i in lst]                  # 243ms

Explanation
The reason why s.replace is so slow is that it does much more than simply map a dictionary. It deals with some edge cases and arguably rare situations, which typically merit more care in any case.
This is an excerpt from replace() in pandas\generic.py.
items = list(compat.iteritems(to_replace))
keys, values = zip(*items)
are_mappings = [is_dict_like(v) for v in values]

if any(are_mappings):
    # handling of nested dictionaries
else:
    to_replace, value = keys, values

return self.replace(to_replace, value, inplace=inplace,
                    limit=limit, regex=regex)

There appear to be many steps involved:

*

*Converting dictionary to a list.

*Iterating through list and checking for nested dictionaries.

*Feeding an iterator of keys and values into a replace function.

This can be compared to much leaner code from map() in pandas\series.py:
if isinstance(arg, (dict, Series)):
    if isinstance(arg, dict):
        arg = self._constructor(arg, index=arg.keys())

    indexer = arg.index.get_indexer(values)
    new_values = algos.take_1d(arg._values, indexer)


text:
Q: Perfect scrollbar not working what am i missing in the following code?
Why is Perfect scrollbar horribly crashing?
It seems it's messing up myDiv scrollbar with browser main scrollbar... any help is appreciated.
<!DOCTYPE html>

    <title>Test</title>
    <meta charset="utf-8" />
    <link href="perfect-scrollbar.min.css" type="text/css" rel="stylesheet">

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Test perfect scrollbar

Thank you

A: Add position:relative to #myDiv
Demo: https://jsfiddle.net/gbfLazpx/243/
CSS:
#myDiv {
  width: 400px;
  height: 400px;
  overflow: auto;
  background-color: #eeeeee;
  margin: auto;
  position: relative;
}

Check the first point here: https://github.com/noraesae/perfect-scrollbar#requirements

the container must have a 'position' css style.


text:
Q: Simulate keyboard input with Lua I usually use java.awt.Robot when I want to simulate keyboard and mouse entries and it work very well.
Recently I heard of another language, Lua, and I try it. I wrote some little programs that work well, but now I'm tying to simulate a keyboard like in java  but I can't make it work.
The most frustrating part is that I find example that use a PressAndReleaseKey('someKey') function in Lua with google, and these codes seems to require no library, however I can't make this function work (they also seems to be always related to logitech so maybe it's only usable within logitech drivers?). So I'm not sure it is what I'm searching for.
So, in short, my question is: How can I simulate a keyboard entry with a Lua program?
For example, if I type in my terminal
lua test.lua

with this file been like that:
while(true) do
     thefunctionIsearch('a')
end

then the program is supposed to type the letter 'a' infinitely.
I am on Linux (Ubuntu) if it something.

A:
these codes seems to require no library

It can't be done without a additional libraries. It can't be done in C without external libraries, and Lua's standard library is implemented entirely in terms of C's standard library.

they also seems to be always related to logitech so maybe it's only usable within logitech drivers

Logitech has keyboards scriptable in Lua, so you're almost certainly seeing a Logitech-specific extension to Lua that's not available in vanilla Lua.

How can I simulate a keyboard entry with a LUA program?

Find or write a module that does it. If you know C, it's very straightforward.
Alternatively, if you can find a shared library that does it for Linux, you could use LuaJIT's FFI to interface with that library directly without having to find/write a module.


text:
Q: How to share Image with some text using Intent code either on FB,Twitter in Android? I have written this code and its successfully working its sending only content and it can share via FB,BlueTooth etc.But i want to share image as well.User will click on image and then   share button and save button will be shown.Now when user click on "share button" the clicked image must be share as Bluetooth,FB,Twitter etc.I have written this code its working for text please let me know how can i send image as well and images are inside the project folder @drawable folder....
public void shareApp()
    {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        //setting MIME type for Sharing Content
        sharingIntent.setType("text/plain");
        sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        String shareBody = "Here is the share content body";
        sharingIntent.putExtra(Intent.EXTRA_EMAIL,new String[] {"abc32@yahoo.com"});
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share via"));

    }


text:
Q: Xamarin, C#, Как сохранить информацию для вторичного использования приложения? Есть приложение, в ней я создаю какой-то объект, заполняю в нем поля, допустим "name" и "phone". Как мне сохранить этот объект, чтобы после перезагрузки приложения мои объекты сохранились?

A: Можно воспользоваться shared preferences:
var sharedPreferences = Android.Preferences.PreferenceManager(Android.App.Application.Context);
var defaultPhone = "+79991112233";
var phone = sharedPreferences.GetString("phone", defaultPhone);

// меняем значение
usin (var editor = sharedPreferences.Edit())
{
    var newPhone = "+79995556677";
    editor.PutString("phone", newPhone);
    editor.Apply();
}

A: Судя по всему, правильный путь — application properties.
В начале работы пишете
var props = Application.Current.Properties;
var name = props.ContainsKey("name") ?
    (string)props["name"] : <тут имя по умолчанию>;
var phone = props.ContainsKey("phone") ?
    (string)props["phone"] : <тут телефон по умолчанию, например, null>;

Когда имя/телефон поменяется, то
Application.Current.Properties["name"] = <новое имя>;
Application.Current.Properties["phone"] = <новый телефон>;
await Application.Current.SavePropertiesAsync();

A: Для таких целей существует AccountStore.

*

*Берем из Nutget Xamarin.Auth

*Пример

    //Сохраняем
    Account account = new Account
    {
    Username = userName
    };
    account.Properties.Add ("Phone", "+11111111111");
    AccountStore.Create ().Save (account, App.AppName);
    //вытаскиваем данные
    AccountStore.Create().FindAccountsForService(App.AppName);

Пример на Xamarin forms. В xamarin Native аналогично все. https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/general/store-credentials/


text:
Q: How to get the duplicated items in the array and select one of them to be presented in the new array in laravel I am building custom permissions system for different sections of a Laravel application.
I have an array of arrays and maybe there is a duplication in the section_id value but with different permission value.
for example i have section_id => 10 exists 3 times here with different 3 permission.
[
    0 => array:2 [▼
      "section_id" => 10
      "permission" => "B"
    ]
    1 => array:2 [▼
      "section_id" => 22
      "permission" => "A"
    ]
    2 => array:2 [▼
      "section_id" => 10
      "permission" => "A"
    ]
    3 => array:2 [▼
      "section_id" => 13
      "permission" => "B"
    ]
    4 => array:2 [▼
      "section_id" => 18
      "permission" => "B"
    ]
    5 => array:2 [▼
      "section_id" => 10
      "permission" => "C"
    ]
]

Now I need to get only the highest permission level available in the array for the duplicated section section => 10
A,B and C are the permissions levels so the priority for A then B then C for the same section , the final result should be like this
[
    0 => array:2 [▼
      "section_id" => 10
      "permission" => "A"
    ]
    1 => array:2 [▼
      "section_id" => 22
      "permission" => "A"
    ]
    2 => array:2 [▼
      "section_id" => 13
      "permission" => "B"
    ]
    3 => array:2 [▼
      "section_id" => 18
      "permission" => "B"
    ]
]

A: You can use collections using sortBy(), unique() and values() chain in this way:
public function test() {
    $p = [
        [
            'section_id' => 10,
            'permission' => 'B'
        ],
        [
            'section_id' => 22,
            'permission' => 'A'
        ],
        [
            'section_id' => 10,
            'permission' => 'A'
        ],
        [
            'section_id' => 13,
            'permission' => 'B'
        ],
        [
            'section_id' => 18,
            'permission' => 'B'
        ],
        [
            'section_id' => 10,
            'permission' => 'C'
        ],
    ];

    $collection = collect($p);
    $sorted = $collection->sortBy(function ($product, $key) {
        return ord($product['permission']);
    })->unique('section_id')->values()->all();
    dd($p, $sorted);
}

Outputs
    array:6 [▼
      0 => array:2 [▼
        "section_id" => 10
        "permission" => "B"
      ]
      1 => array:2 [▼
        "section_id" => 22
        "permission" => "A"
      ]
      2 => array:2 [▼
        "section_id" => 10
        "permission" => "A"
      ]
      3 => array:2 [▼
        "section_id" => 13
        "permission" => "B"
      ]
      4 => array:2 [▼
        "section_id" => 18
        "permission" => "B"
      ]
      5 => array:2 [▼
        "section_id" => 10
        "permission" => "C"
      ]
    ]
    array:4 [▼
      0 => array:2 [▼
        "section_id" => 22
        "permission" => "A"
      ]
      1 => array:2 [▼
        "section_id" => 10
        "permission" => "A"
      ]
      2 => array:2 [▼
        "section_id" => 13
        "permission" => "B"
      ]
      3 => array:2 [▼
        "section_id" => 18
        "permission" => "B"
      ]
    ]

A: Try this:
$myArray = array(
   ["section_id" => 10, "permission" => "B"],
   ["section_id" => 22, "permission" => "A"],
   ["section_id" => 10, "permission" => "A"],
   ["section_id" => 13, "permission" => "B"],
   ["section_id" => 18, "permission" => "B"],
   ["section_id" => 10, "permission" => "C"]);

$sectionArr  = array_column($myArray, 'section_id');
$permissionArr = array_column($myArray, 'permission');

array_multisort($sectionArr, SORT_ASC, $permissionArr, SORT_ASC, $myArray);
$newArray = array();
$tempSection = array();
foreach($myArray as $key => $singleArray){
  if(!in_array($singleArray['section_id'], $tempSection)){
      $tempSection[] = $singleArray['section_id'];
      $newArray[] = ["section_id" => $singleArray['section_id'], "permission" => $singleArray['permission']];
    }
}

print_r($newArray);


text:
Q: Jquery Ajax replace DIV in first time but not in second time(MVC4) View
@section Scripts{

    }

                    <input type="text" id="SearchName"/>

                    Search

            T_T

Controller
[HttpPost]
        public ActionResult Contribute(String id)
        {
                String UserName = id;
                PMSDBContext PMP = new PMSDBContext();
                List<_ContributeViewModel> result = new List<_ContributeViewModel>();

                result = PMP.Users
                             .Join(PMP.Friendships, u => u.UserID,
                             f => f.FriendID,
                             (u, f) => new { u, f })
                             .Where(m => m.f.UserID == 1 && m.u.Name.Contains(UserName) && m.f.Status == 1)
                             .Select(s => new _ContributeViewModel
                             {
                                 UserID = s.u.UserID,
                                 PhoneNo=s.u.PhoneNo,
                                 Facebook=s.u.Facebook,
                                 Name=s.u.Name
                             }
                             ).ToList();

            return View("UserSearch",result);
        }

UserSearch View
@model List<PMS.View_Model._ContributeViewModel>
@{
    ViewBag.Title = "SearchResult";
}

            Search Result

        Name
        PhoneNo
        FaceBook

    @foreach (var item in Model.Where(model => model.UserID != null))
    {

                @Html.DisplayFor(model => item.Name)

                @Html.DisplayFor(model => item.PhoneNo)

                @Html.DisplayFor(model => item.Facebook)

    }

When I first click Search button with some text in textbox,UserSearch View replace "T_T" with database results but second time page reloaded and "T_T" replace UserSearch View and third time User Search View replace "T_T" again and  that happens continuously...Question is what can I do UserSearch View to replace "T_T" in every click?

A: Instead of returning complete view you can use tagbuilder to construct the html markup and send that
[HttpPost]
public MvcHtmlString Contribute(String id)
{
   String UserName = id;
   PMSDBContext PMP = new PMSDBContext();
   List<_ContributeViewModel> result = new List<_ContributeViewModel>();
   result = PMP.Users
               .Join(PMP.Friendships, u => u.UserID,
                                 f => f.FriendID,
                                 (u, f) => new { u, f })
                                 .Where(m => m.f.UserID == 1 && m.u.Name.Contains(UserName) && m.f.Status == 1)
                                 .Select(s => new _ContributeViewModel
                                 {
                                     UserID = s.u.UserID,
                                     PhoneNo=s.u.PhoneNo,
                                     Facebook=s.u.Facebook,
                                     Name=s.u.Name
                                     }
                                     ).ToList();

    StringBuilder output = new StringBuilder();
    TagBuilder ulTag = new TagBuilder("ul");
    foreach (var item in result )
    {

                output.Append(ulTag.ToString());
                ulTag = new TagBuilder("ul");

     }
     output.Append(ulTag.ToString();
     return output.ToString();
}

I think the problem you are facing is due to an entire page being rendered and problems with its replacement in the div.

A: Try below code
$('#UserSearch').click(function () {
     $.ajax({
         url: '/Project/Contribute',
         dataType:'html',
         type: 'POST',
         data: { id:$('#SearchName').val() },
         success: function (result) {
           $('#ajaxsample').html(result);
         }
    });
    return false;
});

Your Action Will be
[HttpPost]
public PartialViewResult Contribute(String id)
{
     //Your logic. .....
     return PartialView("UserSearch",result);
}

Normally it will work...


text:
Q: How to call properties from other classes I have a ViewController Class hooked to a button with a method as follows:
 #import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.clickCount = 0;

    NSLog(@"Click count = %@", self.clickCount);

Some more code that sets an image for the button etc...

}

The property clickCount has been declared in the h file:
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property int clickCount;
- (IBAction)BasicAction:(id)sender;

@end

What I would like to do, is create a different class that picks up this property clickCount and does something independently. I am a beginner so I have no idea how to do this. Should I create another generic class and create an instance of my view controller then access the property that way, and if so how would I get something basic to print to the console like i.e.:
if (instanceOfViewController.clickCount % 2 = 0){
    NSLog(@"Player 1 is playing");
} else {
    NSLog(@"Player 2 is playing");
}

I tried this but although the first NSLog with the click count appears, the other messages don't.
Or should I use delegation? If so, what is the best way to go about it?
I know I could just write everything in my view controller but, although I am just beginning to program -so my knowledge is very limited- I am trying to organise my program in a way that my view controller doesn't become really long. Also I am trying to think in term of different objects interacting with each other. Can you point me in the right direction?
Thanks


text:
Q: remove x ticks but keep grid lines I have a Pyplot plot, which I want to add gridlines to. I did this using:
plt.grid(True)

I then removed my x ticks using:
ax1.xaxis.set_visible(False)

My x ticks were removed, but so were the x grid lines. I would like them to stay.
Is there a way I can do this please?

A: from matplotlib.ticker import NullFormatter
ax.xaxis.set_major_formatter(NullFormatter())

A: Try this:
plt.grid(True)
ax.xaxis.set_ticklabels([])

It should work. The grid will be intact, but there won't be any tick labels. If you don't want the ticks too, add:
ax.xaxis.set_ticks_position('none')


text:
Q: Why do I get "invalid operands types" in one occasion but not in the other, similar one? I have two strings, the first one is concatenated like this:
  dataString = String(dates + "," + times + "," + temp[0] + "," + hum[0] + "," +
                      temp[1] + "," + hum[1] + "," + temp[2] + "," + hum[2] +
                      "," + temp[3] + "," + hum[3]);

And the other one:
dataLog = String("," + airTemp[1] + "," + hum[1] + "," + floorTemp[1]);

dates, times are strings; hum, temp, airTemp, and floorTemp are floats.
I've got no problem with the first one, but with the second one, I always get this error message:
error: invalid operands of types 'const char [2]' and 'float' to binary 'operator+'

However, if I use String() to convert the floats, it works just fine. But then again, I don't have to convert the floats in the first one into strings.
My problem is solved by using String(), but why does this happen?


text:
Q: How to connect to MySQL db in ASP.NET? I tried it this way to connect to a database using MySQL, however when I run the code Response.Write does not write anything at all to the website.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using MySql.Data.MySqlClient;

public partial class _Default : System.Web.UI.Page
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        // if it is not a post back method, page renders for first time
        {
            connectdb();
        }
    }

    private void connectdb()
    {
        server = "localhost";
        database = "first_db";
        uid = "root";
        password = "";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" +
            database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);

        try
        {
            connection.Open();
            Console.ReadKey();
            Response.Write("connection opened");
        }
        catch (MySqlException ex)
        {
            //When handling errors, you can your application's response based
            //on the error number.
            //The two most common error numbers when connecting are as follows:
            //0: Cannot connect to server.
            //1045: Invalid user name and/or password.
            switch (ex.Number)
            {
                case 0:
                    Response.Write("Cannot connect to server.  Contact administrator");
                    break;

                case 1045:
                    Response.Write("Invalid username/password, please try again");
                    break;
            }
        }
    } //end of connectdb
}

A: Your code is suppressing lots of exception possibilities.
I suggest you add this to the end of your switch statement.
      default:
                Response.Write(ex.Number + ": " + ex.Message);
                break;

You'll likely find out what's wrong.


text:
Q: Detect whether external script has loaded Using JavaScript, is there a way to detect whether or not an external script (from a third-party vendor) has completely loaded?
The script in question is used to pull in and embed the markup for a list of jobs and, unfortunately, doesn't make use of any variables or functions. It uses document.write to output all of the content that gets embedded in my page.
Ideally, I'd like to display some kind of loading message while I'm waiting for the external script to load, and if it fails to load, display a "We're sorry, check back later..." message.
I'm using jQuery on the site, but this external script is called before I make the jQuery call.
Here's what the document.write stuff from the external script looks like:
document.write('
');
document.write("

            Position Title

City, State

Job Company Name

");

A: Script tags block downloads, so as long as the content dependent on your script is below where your script it loaded, you should be fine. This is true even if the script is in-line in the body of your page.
This website has a great example of how this works.
This obviously does not work if you're loading the scripts asynchronously.

Scripts without async or defer attributes are fetched and executed immediately, before the browser continues to parse the page.

Source: MDN

A: You could put a script block after it on the page:

A: Thanks for the assistance above, especially ngmiceli for the Steve Souders link!
I decided to take what's probably a "lazy" approach, and also forego the "loading" message:
$(document).ready(function(){
    if ($('.jt_job_list').length === 0){
        $('#job-board').html("
We're sorry, but the Job Board isn't currently available. Please try again in a few minutes.
");
    };
});

Pretty simple, but I'm looking to see if an element with the .jt_job_list class is in the dom. If it isn't, I display an error message.

A: Attach an function to the load event:


text:
Q: Vim code completion doesn't work after including a standard header I have to develop my project in text-mode debian linux. I'm using Vim and I installed the clang_completion plugin on it. I made .clang_completion file in root of my project :
-I.
-I/usr/include
-I/usr/include/c++/4.6

When I write a program like below, the completion works fine.
//#include <stdio.h>
int main()
{
  struct A
  {
    int x, y;
  };

  A a;
  a. // After putting dot, the suggestion popup appears

  return 0;
}

However, after removing the comment of first line, it doesn't work! How can I overcome this issue?

A: I found the easiest way to get clang_complete to work is to use the provided cc_args.py file.
when compiling a project use clang_complete/bin/cc_args.py instead of gcc/g++
This will generate the correct .clang_complete file with all libraries and dependencies.
Provided the clang_complete source directory in your home folder.
Example Makefile:
CXX=$(HOME)/clang_complete/bin/cc_args.py g++

all:
    $(CXX) main.cpp

A: I've successfully used the clang_complete plugin in the past (now I just use cscope and ctags, which I consider enough).
Including external headers worked fine in my configuration, but, as the clang complete plugin page specifies, the file in which to put include paths (or any other flag you may want to pass to the clang compiler), must be named .clang_complete and not .clang_completion.
Also, I used to put the options on a single line, just as I was going to pass the plain content of the .clang_complete file as a command line option (don't know if separating lines with \ will work).
Hope this helps.


text:
Q: How to write an initWith... on a viewController I learned a very painful lesson about how to ensure your outlets are nil on a view controller's viewDidLoad, and that's by writing an initWith... method of your own.
-(id)initWithDoohickey:(SomeDoohickey*)doohickey
    {
        self = [super init];
        if (self)
        {
            theDoohickey = doohickey;
        }
        return nil;
    }

Now when you call this method, instead of initWithNibName, or simply init, your view outlets will be nil, and you'll run into all kinds of debugging nightmares.
So I see two solutions here...
(1) Call init or initWithNibName and let it do it's thing, and follow that with a classInQuestion configureWithDoohickey:(SomeDoohickey*)doohickey
or (2)
figure out how to properly write an initWith... method that actually loads the nib properly, while also allowing me to pass in whatever config variables I want in the same call.
I'd like to know how to do (2).

A: Simply replace your call to [super init]; with a call to [super initWithNibName:...];.
Obviously you need to pass in the correct arguments.

A: The problem you have is that you didn't properly chain the initializers. A subclass's initialization process must (eventually) call its superclass's designated initializer. The designated initializer ensures that all of a class's data is correctly set up.
If you don't call the superclass's DI, it's not able to set the properties that were defined in the superclass.
The simple init that you're using is not UIViewController's designated intializer; initWithNibName:bundle: is. As rmaddy said, that is the method you should use in your subclass's own designated intializer.
Initializers in the subclass can use each other, as long as one of them eventually passes up to the superclass's DI.
(As an aside, this relationship has been formalized in Swift. Initializer chaining is actually part of the language, rather than just a convention. This can be confusing, but interestingly, the way you wrote initWithDoohickey: would not have even compiled in Swift.)


text:
Q: Convert Array of RGB Integers to Bitmap We know that, we can get rgb of bitmap image with using the code as follow :
BufferedImage img = ImageIO.read(new File(bitmapURL));
int[] pixels = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());

And, after executing this parts of code, we have an array of integers that contains 4 bytes for Alpha, Red, Green and Blue colors of any pixel. So, i want to know that how can we convert an array of integers like int [] myPixels; to Bitmap ? Could any one please help me to reach this?
Thanks in advance :)

A: You can directly use this :
image.setRGB(0, 0, width, height, pixels, 0, width);

Source

A:
BufferedImage im = new BufferedImage(width, height);

for (int i = 0; i < width; i++) {
  for (int j = 0; j < height; j++) {
    im.setRGB(...);
  }
}


text:
Q: Does App Framework have connection to JQMobi? I'm a bit curious as to why there is no official site for JQMobi. As of now, it seems like the only place where I can download JQMobi is through github. And every time I search for JQMobi on Google, Intel's APP Framework shows up.
Is there some kind of connection between JQMobi and Intel's APP Framework? Are they the same or is JQMobi not supported anymore?

A: jqMobi was renamed to Intel App Framework.
Intel acquired AppMobi in 2013, the company that was maintaining jqMobi framework, it is now called Intel App Framework.


text:
Q: React Typescript interface I get a problem when making an interface on Typescript!
export interface Content {
  uuid?: string;
  brand_id?: string;
  brand_name?: string;
  is_active?: boolean;
}

export interface Pageable {
  sort?: Sort;
  pageSize?: number;
  pageNumber?: number;
  offset?: number;
  unpaged?: boolean;
  paged?: boolean;
}

export interface Sort {
  sorted?: boolean;
  unsorted?: boolean;
  empty?: boolean;
}

export interface BrandData {
  content?: Content;
  pageable?: Pageable;
  numberOfElements?: number;
  number?: number;
  sort?: Sort;
  size?: number;
  first?: boolean;
  last?: boolean;
  empty?: boolean;
}
export interface BrandResponse {
  readonly data?: BrandData[];
}

and then i want to get data in react component like this
const { brands } = useSelector((state: AppState) => state.catalogs.brands);
const [brandData, setBrandData] = React.useState(brands.data);
const [currentPage, setCurrentPage] = React.useState(brandData.pageable.pageNumber);

then the error exits like this
Property 'pageable' does not exist on type 'BrandData[]'.


text:
Q: Ошибка java.lang.NullPointerException при нажатии на элемента RecyclerView из Фрагмента Вопросов с похожими проблемами не нашел и поэтому решил задать свой. Не могу ловить клик на элемент RecyclerView из Фрагмента. У меня есть Fragment который показывает данные в виде списка. Этот список создается с помощью RecyclerView. Мне нужно чтобы при нажатии на элемента открыть другое активити. Но при нажатии я получаю вот это:
 java.lang.NullPointerException: Attempt to invoke interface method 'void com.app.demo.ItemClickListener.onItemClick(android.view.View, int)' on a null object reference

Мой интерфейс ItemClickListener:
public interface ItemClickListener {
    void onItemClick(View view, int position);
}

Код на ContactsFragment для реакции на клик который не выполняется:
 @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(getActivity(), "It works!!", Toast.LENGTH_SHORT).show();
    }

Код на адаптере RecyclerView на которого указывает стектрейс:
  @Override
public void onBindViewHolder(ContactsAdapter.MyViewHolder holder, final int position) {

      holder.itemView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             listener.onItemClick(v,position);
         }
     });

Стектрейс говорит что ошибка это здесь :  listener.onItemClick(v,position);
Если убрать эту строку и например добавить туда Toast тогда никаких ошибок не возникает и при нажатии на элемент этот Toast показывается.
Мне нужно знать как решить эту проблему?

A: Понял что мой способ получении клика от RecyclerView работает для активити но не для фрагментов. Изменил код с помощью этой статьи и проблема решилась.
Код ViewHolder'a из адаптера для RecyclerView :
     public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
            private ItemClickListener mListener;

            ViewHolder(View v, ItemClickListener listener) {
                super(v);

                mListener = listener;
                v.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
               mListener.onItemClick(v, getAdapterPosition());
            }
        }
  public MyAdapter(List<Contact> myList,ItemClickListener listener) {
        this.myList = myList;
             mListener = listener;
    }
    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row,parent,false);

        return new ViewHolder(view,mListener);
    }

Код из фрагмента на котором находится RecyclerView из которого нужно ловить клики(Этот код находится на onCreateView):
ItemClickListener listener = new ItemClickListener() {
    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(getActivity(), "It works!!", Toast.LENGTH_SHORT).show();
    }
};

mAdapter = new ContactsAdapter(contacts,listener);
recyclerView.setAdapter(mAdapter);


text:
Q: closest value and data frame index index of all data frame elements of a list I have a list containing data frames:
test <- list()
test[[1]] <- data.frame(C1=c(0.2,0.4,0.5), C2=c(2,3.5,3.7), C3=c(0.3,4,5))
test[[2]] <- data.frame(C1=c(0.1,0.3,0.6), C2=c(3.9,4.3,8), C3=c(3,5.2,10))
test[[3]] <- data.frame(C1=c(0.4,0.55,0.8), C2=c(8.9,10.3,14), C3=c(7,8.4,11))

I´d like to get the line among all data frames lines inside this list which column (e.g.C2 in this example) has the closest value to each element in a vector "vec" (below), as well as the list index (1, 2 or 3 in this example) where it happened.
vector <- c(3, 14.4, 7, 0)

The desired answer would be something like:
list.index    line.number.in.df    C1  C2 C3
     1              2              0.4 3.5 4
     3              3              0.8 14 11
     2              3              0.6  8 10
     1              1              0.2  2 0.3

I could manage to use lapply to get 10% of the problem solved for a single value, but couldn´t do it for a bunch of values (vector) besides getting all list elements dataframe lines where the closest value as found (not only a single line among all data frames),and could not get the corresponding list index as well, i.e.
value <- 3
lapply(test, function(x) x[which.min(abs(value-x$C2)),])

Result I got:
[[1]]
  C1  C2 C3
2 0.4 3.5  4

[[2]]
  C1  C2 C3
1 0.1 3.9  3

[[3]]
  C1  C2 C3
1 0.4 8.9  7

Would anyone be so kind and patient to get me further on this?
Thanks in advance and Happy New Year.

A: Here is a dplyr approach. We can generate the list.index and line.number.in.df for each dataframe and then bind_rows them together. Next, slice the rows where C2 contains the closest value for each number in that vector.
library(dplyr)

test <- list(structure(list(C1 = c(0.2, 0.4, 0.5), C2 = c(2, 3.5, 3.7
), C3 = c(0.3, 4, 5)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(C1 = c(0.1, 0.3, 0.6), C2 = c(3.9, 4.3,
8), C3 = c(3, 5.2, 10)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(C1 = c(0.4, 0.55, 0.8), C2 = c(8.9, 10.3,
14), C3 = c(7, 8.4, 11)), class = "data.frame", row.names = c(NA,
-3L)))

vector <- c(3, 14.4, 7, 0)

test %>%
  lapply(tibble::rowid_to_column, "line.number.in.df") %>%
  bind_rows(.id = "list.index") %>%
  slice(vapply(vector, \(x) which.min(abs(x - C2)), integer(1L)))

Output is
  list.index line.number.in.df  C1   C2   C3
1          1                 2 0.4  3.5  4.0
2          3                 3 0.8 14.0 11.0
3          2                 3 0.6  8.0 10.0
4          1                 1 0.2  2.0  0.3

A: You could exploit the substrings of the names.
(w <- sapply(v, \(v)
            names(which.min(abs(unlist(setNames(test, seq_along(test))) - v)))))
# [1] "2.C31" "3.C23" "3.C31" "2.C11"

t(mapply(\(x, y) c(list=x, line=y, test[[x]][y, ]),
         as.numeric(substr(w, 1, 1)), as.numeric(substring(w, 5)))) |>
  as.data.frame()
#   list line  C1  C2 C3
# 1    2    1 0.1 3.9  3
# 2    3    3 0.8  14 11
# 3    3    1 0.4 8.9  7
# 4    2    1 0.1 3.9  3

Note: R >= 4.1 used.

Data:
test <- list(structure(list(C1 = c(0.2, 0.4, 0.5), C2 = c(2, 3.5, 3.7
), C3 = c(0.3, 4, 5)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(C1 = c(0.1, 0.3, 0.6), C2 = c(3.9, 4.3,
8), C3 = c(3, 5.2, 10)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(C1 = c(0.4, 0.55, 0.8), C2 = c(8.9, 10.3,
14), C3 = c(7, 8.4, 11)), class = "data.frame", row.names = c(NA,
-3L)))

v <- c(3, 14.4, 7, 0)

A: I hope this is what you are looking for. It finds the value in each of the columns per element of test, that is closest to the values in vector.
#install.packages('birk')
library(birk) # required for which.closest()

# find which of the values across the columns C1:C3 in each element of test are closest
# to the values of vector and return the corresponding row numbers
x <- sapply(1:length(vector), \(x) sapply(test, \(i) apply(i, 2, \(j) which.closest(j, vector[x]))))
x <- apply(x, 1, \(x) as.data.frame(table(x)))
x <- lapply(x, \(i) i[which.max(i[, 2]), ])
row_numbers_df <- as.numeric(matrix(do.call(rbind, x)[['x']]))

# extract the values in each of the column C1:C3 corresponding to row_numbers_df
vals <- array(0, dim = length(row_numbers_df))
for (i in 1:length(row_numbers_df)) { vals[i] <- do.call(cbind, test)[row_numbers_df[i], i] }

# how many columns does each data.frame embedded in test have?
unique_number_of_cols <- unique(sapply(test, ncol))

# store results in a data.frame
r <- \(x) round(x, 1)
out <- data.frame(
  seq_len(length(test)),
  r(rowMeans(matrix(row_numbers_df, ncol = unique_number_of_cols, byrow = TRUE))),
  matrix(vals, ncol = unique_number_of_cols, byrow = TRUE)
)
names(out) <- c('list.index', 'line.number.in.df', sapply(test, colnames)[, 1])

Result
> out
  list.index line.number.in.df  C1  C2 C3
1          1               3.0 0.5 3.7  5
2          2               1.7 0.6 3.9  3
3          3               1.7 0.8 8.9  7

Alternatively, if you really want to have each line.number.in.df per unique column, then you can easily store them as separate columns in out.
x <- sapply(1:length(vector), \(x) sapply(test, \(i) apply(i, 2, \(j) which.closest(j, vector[x]))))
x <- apply(x, 1, \(x) as.data.frame(table(x)))
x <- lapply(x, \(i) i[which.max(i[, 2]), ])
row_numbers_df <- as.numeric(matrix(do.call(rbind, x)[['x']]))
names(row_numbers_df) <- do.call(c, lapply(test, names))

row_numbers_df
vals <- array(0, dim = length(row_numbers_df))
for (i in 1:length(row_numbers_df)) { vals[i] <- do.call(cbind, test)[row_numbers_df[i], i] }

unique_number_of_cols <- unique(sapply(test, ncol))

out <- data.frame(
  seq_len(length(test)),
  split(row_numbers_df, names(row_numbers_df)),
  matrix(vals, ncol = unique_number_of_cols, byrow = TRUE)
)
column_names <- sapply(test, colnames)[, 1]
names(out) <- c('list.index',
                paste0('line.number.in.df.', column_names),
                column_names)

Result
> out
  list.index line.number.in.df.C1 line.number.in.df.C2 line.number.in.df.C3  C1  C2 C3
1          1                    3                    3                    3 0.5 3.7  5
2          2                    3                    1                    1 0.6 3.9  3
3          3                    3                    1                    1 0.8 8.9  7


text:
Q: How to display values of a property from item in ListBoxes multibinding in a TextBox I have a TextBox and I want to show value of a property of the selected item in code behind (with some event, for example, MouseDown)
Property is of type Int16.
I saw similar questions here, but:
TextBox2.Text = ((Helmet) listhelmets.SelectedItems).protection;

Doesn't work for me and so don't other advice I saw.
<ListBox x:Name="listweapons" Height="214" Width="248" ItemsSource="{Binding ListWeapon}"
         IsSynchronizedWithCurrentItem="True" Canvas.Left="211" Canvas.Top="72"
         PreviewMouseLeftButtonDown="weapons_PreviewMouseLeftButtonDown"
         PreviewMouseMove="weapons_PreviewMouseMove"
         SelectedValuePath="attack">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Path=Image}" Width="56" Height="61"/>
                <TextBox Height="30" Width="30">
                    <Binding Path="_attack" />
                </TextBox>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

A: You can't cast object of type ListBox.SelectedItemCollection to type Helmet, So you should use SelectedItem property of the listhelmets instead of SelectedItems like this:
TextBox2.Text = ((Helmet) listhelmets.SelectedItem).protection;

Also don't forget to use ToString() in the end of the line if protection is not string.


text:
Q: Dealing with Empty Fields I am new to stormcrawler and elasticsearch in general. I am currently using stormcrawler 2.0 to index website data (including non-HTML items such as PDF's and Word Documents) into elasticsearch. In some cases, the metadata of PDF's or Word documents do not contain a title so the field is stored blank/null in elasticsearch. This is unfortunately causing issues in the webapp I am using to display search results (search-ui). Is there a way I can have stormcrawler insert a default value of "Untitled" into the title field if none exists in the metadata?
I understand that elasticsearch has a null_value field parameter, but if I understand correctly that parameter cannot be used for text fields and only helps with searching.
Thanks!

A: One option would be to write a custom ParseFilter to give an arbitrary value to any missing key or a key with an empty value. The StormCrawler code has quite a few examples of ParseFilters, see also the WIKI.
The same could be done as a custom Bolt placed between the parser and the indexer; grab the metadata and normalise to your heart's content.


text:
Q: facing the below issue while setting thoughput in packer json file, need help to resolve this issue Error:
Template validation failed. Errors are shown below.
Errors validating build 'amazon-ebs'. 1 error(s) occurred:

*

*unknown configuration key: "launch_block_device_mappings[0].throughput"

script returned exit code 1
Code:
"launch_block_device_mappings": [
{
"device_name": "/dev/sda1",
"volume_size": 40,
"volume_type": "gp2",
"volume_size": 80,
"volume_type": "gp3",
"throughput": 270,
"delete_on_termination": true"

A: I had this issue too and I updated my packer version to 1.6.6 and that worked.


text:
Q: Pandas: populating column values with date and time string based on conditions I have a Pandas dataframe df that looks as follows:
created_time                         action_time
2021-03-05T07:18:12.281-0600         2021-03-05T08:32:19.153-0600
2021-03-04T15:34:23.373-0600         2021-03-04T15:37:32.360-0600
2021-03-01T04:57:47.848-0600         2021-03-01T08:37:39.083-0600

import pandas as pd

df = pd.DataFrame({'created_time':['2021-03-05T07:18:12.281-0600', '2021-03-04T15:34:23.373-0600', '2021-03-01T04:57:47.848-0600'],
                  'action_time':['2021-03-05T08:32:19.153-0600', '2021-03-04T15:37:32.360-0600', '2021-03-01T08:37:39.083-0600']})

I then create another column which represents the the difference in minutes between these two columns:
df['elapsed_time'] = (pd.to_datetime(df['action_time']) - pd.to_datetime(df['created_time'])).dt.total_seconds() / 60

df['elapsed_time']

elapsed_time
74.114533
3.149783
219.853917

We assume that "action" can only take place during business hours (which we assume to start 8:30am).
I would like to create another column named created_time_adjusted, which adjusts the created_time to 08:30am if the created_time is before 08:30am).
I can parse out the date and time string that I need, as follows:
df['elapsed_time'] = pd.to_datetime(df['created_time']).dt.date.astype(str) + 'T08:30:00.000-0600'

But, this doesn't deal with the conditional.
I'm aware of a few ways that I might be able to do this:
replace
clip
np.where
loc

What is the best (and least hacky) way to accomplish this?
Thanks!

A: First of all, I think your life would be easier if you convert the columns to datetime dtypes from the go. Then, its just a matter of running an apply op on the 'created_time' column.
df.created_time = pd.to_datetime(df.created_time)
df.action_time = pd.to_datetime(df.action_time)
df.elapsed_time = df.action_time-df.created_time
time_threshold = pd.to_datetime('08:30').time()
df['created_time_adjusted']=df.created_time.apply(lambda x:
                                                  x.replace(hour=8,minute=30,second=0)
                                                  if x.time()<time_threshold else x)

Output:
>>> df
                      created_time                      action_time            created_time_adjusted
0 2021-03-05 07:18:12.281000-06:00 2021-03-05 08:32:19.153000-06:00 2021-03-05 08:30:00.281000-06:00
1 2021-03-04 15:34:23.373000-06:00 2021-03-04 15:37:32.360000-06:00 2021-03-04 15:34:23.373000-06:00
2 2021-03-01 04:57:47.848000-06:00 2021-03-01 08:37:39.083000-06:00 2021-03-01 08:30:00.848000-06:00

A: df['created_time']=pd.to_datetime(df['created_time'])#Coerce to datetime
df1=df.set_index(df['created_time']).between_time('00:00:00', '08:30:00', include_end=False)#Isolate earlier than 830 into df
df1['created_time']=df1['created_time'].dt.normalize()+ timedelta(hours=8,minutes=30, seconds=0)#Adjust time
df2=df1.append(df.set_index(df['created_time']).between_time('08:30:00','00:00:00',  include_end=False)).reset_index(drop=True)#Knit before and after 830 together
df2


text:
Q: Text file to JSON in Java? I have a text file like this demo.txt
name        : Cherry.API.DEV
version2    : Test
uuid        : 0492389a-43243-ewr234342-343d
xx          : {@{fdsfsdfsf}
lastSession : 0.0
activeOK    : True
learn       : ok

I want to read demo.txt file and then convert as a JSON like this
{"name":"Cherry.API.CI", "variableName":{"module":"Cherry","ID" : "0492389a-43243-ewr234342-343d","systemdebug": "True"}}

A: In Groovy it could be:
import groovy.json.JsonOutput

def str = """name        : Cherry.API.DEV
version2    : Test
uuid        : 0492389a-43243-ewr234342-343d
xx          : {@{fdsfsdfsf}
lastSession : 0.0
activeOK    : True
learn       : ok
"""

def map = [:]
str.splitEachLine(~':', { List<String> list ->
    map.put(list[0].trim(), list[1].trim())
})

def json = JsonOutput.toJson(map)
println json

assert json == '{"name":"Cherry.API.DEV","version2":"Test","uuid":"0492389a-43243-ewr234342-343d","xx":"{@{fdsfsdfsf}","lastSession":"0.0","activeOK":"True","learn":"ok"}'

It prints:
{"name":"Cherry.API.DEV","version2":"Test","uuid":"0492389a-43243-ewr234342-343d","xx":"{@{fdsfsdfsf}","lastSession":"0.0","activeOK":"True","learn":"ok"}

The solution in Java with jackson:
BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/test.txt")));
String line;
Map<String, String> map = new LinkedHashMap<>();
while ((line = reader.readLine()) != null) {
    String[] tokens = line.split(":");
    if (tokens != null && tokens.length > 1) {
        String key = tokens[0];
        String value = tokens[1];
        if (key != null && value != null) {
            map.put(key.trim(), value.trim());
        }
    }
}
String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);


text:
Q: Is there a way to generate pdf with remix.run Hosted remix app with supabase as db on netlify. Is there a way to generate pdf document using remix ?

A: Remix has a feature called Resource Routes which let you create endpoints returning anything.
Using them, you could return a Response with a PDF, how to generate the PDF will depend on what libraries you are using, if you use something like React PDF you could do something like this:
// routes/pdf.tsx
import { renderToStream } from "@react-pdf/renderer";
// this is your PDF document component created with React PDF
import { PDFDocument } from "~/components/pdf";
import type { LoaderFunction } from "remix";

export let loader: LoaderFunction = async ({ request, params }) => {
  // you can get any data you need to generate the PDF inside the loader
  // however you want, e.g. fetch an API or query a DB or read the FS
  let data = await getDataForThePDFSomehow({ request, params });

  // render the PDF as a stream so you do it async
  let stream = await renderToStream(<PDFDocument {...data} />);

  // and transform it to a Buffer to send in the Response
  let body: Buffer = await new Promise((resolve, reject) => {
    let buffers: Uint8Array[] = [];
    stream.on("data", (data) => {
      buffers.push(data);
    });
    stream.on("end", () => {
      resolve(Buffer.concat(buffers));
    });
    stream.on("error", reject);
  });

  // finally create the Response with the correct Content-Type header for
  // a PDF
  let headers = new Headers({ "Content-Type": "application/pdf" });
  return new Response(body, { status: 200, headers });
}

Now when the user goes to /pdf it will get the PDF file back, you could also use an iframe to show it on the HTML.

If you don't use React PDF, change the render part to use the library you are using, and keep the headers and the Response creation part.


text:
Q: VBA text to columns with "" delimiters I will be quick.
I have a variable 'strLine' with text:
The exact string will look like that:
"Text1","Text2","Text3","Text4","Text5"
So, delimiter in my case is: "
How I can extract text and write it in columns.
Expecting results in cells:
A1=Text1
B1=Text2
C1=Text3
D1=Text4
E1=Text5

Thanks

A: Use Split function, it'll return a 0-based array (ergo +1 in cells) :
Sub test_Andy()

Dim StrLine As String
Dim Str() As String

StrLine = Range("A2").Value 'If your value is in A2
'If you input the value manually, not really practical with so much "
StrLine = Chr(34) & "Text1" & Chr(34) & "," & Chr(34) & "Text2" & Chr(34) & "," & Chr(34) & "Text3" & Chr(34) & "," & Chr(34) & "Text4" & Chr(34) & "," & Chr(34) & "Text5" & Chr(34)
Debug.Print StrLine '"Text1","Text2","Text3","Text4","Text5"

Str = Split(StrLine, ",")

Dim i As Integer
For i = LBound(Str) To UBound(Str)
    Cells(1, i + 1) = Str(i)
    Cells(2, i + 1) = Replace(Str(i), Chr(34), vbNullString)
Next i

End Sub

A: You can use Split to split the text into an array, then remove the " from the start and the end of the parts using Mid :
strText = """Text1"",""Text2"",""Text3"",""Text4"",""Text5"""
aSplit = Split(strText, ",")
For Each strCurrent in aSplit
    MsgBox Mid(strCurrent, 2, Len(strCurrent) - 2)
Next

Remark : You might want to add some checks to ensure that there is a " at the start and end before removing them.

A: edited to simulate a StrLine loop:
Dim iRow As Long
irow = 1

For Each StrLine In StrLines '<--' assuming a loop through many StrLines
    Str = Split(Replace(StrLine, """", ""), ",")
    Cells(iRow, 1).Resize(, UBound(Str) - LBound(Str)).Value = Str
    iRow = iRow + 1
Next


text:
Q: How to update a value in Sql with c# Can someone help finding the right formula for Update
protected void Button1_click(object sender, EventArgs e)
    {

        string connectionString1 = WebConfigurationManager.ConnectionStrings["kickstarterConn"].ConnectionString;
        SqlConnection com = new SqlConnection(connectionString1);
        com.Open();
        string sql1 = "UPDATE Project SET Foundet = @Foundet ";
        SqlCommand cmd1 = new SqlCommand(sql1, com);

        cmd1.Parameters.AddWithValue("@Foundet", TextBox7.Text);
        com.Close();
    }

A: You should execute the command.
com.Open();
string sql1 = "UPDATE Project SET Foundet = @Foundet ";
SqlCommand cmd1 = new SqlCommand(sql1, com);
cmd1.Parameters.AddWithValue("@Foundet", TextBox7.Text);
cmd1.ExecuteNonQuery();
com.Close();


text:
Q: How to bind grid view in entity framework one to one relationship I want to know how to show data in grid view by using entity framework.  My table structure is
StudentId StudentName CourseId
1       SS              1
2       AA              2

CourseId CourseName
1           English
2           Mathematics

Currently I can show Student id and name in grid view, but cant show CourseName.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="EntityDataSource1"
            Width="527px">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="Model" ReadOnly="True"
                    SortExpression="StudentId" />
                <asp:BoundField DataField="StudentName" HeaderText="Costs" ReadOnly="True"
                    SortExpression="StudentName" />
            </Columns>
        </asp:GridView>
        <asp:EntityDataSource ID="EntityDataSource1" runat="server"
            ConnectionString="name=CarContext" DefaultContainerName="CarContext"
            EnableFlattening="False" EntitySetName="Cars" Select="it.[StudentId], it.[StudentName]">
        </asp:EntityDataSource>

Any help is greatly appreciated.

A: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataSourceID="EntityDataSource1"
            Width="527px">
            <Columns>
                <asp:BoundField DataField="StudentId" HeaderText="Model" ReadOnly="True"
                    SortExpression="StudentId" />
                <asp:BoundField DataField="StudentName" HeaderText="Costs" ReadOnly="True"
                    SortExpression="StudentName" />
                <asp:BoundField DataField="CourseName" HeaderText="Course" ReadOnly="True"
                    SortExpression="CourseName" />
            </Columns>
        </asp:GridView>
        <asp:EntityDataSource ID="EntityDataSource1" runat="server"
            ConnectionString="name=CarContext" DefaultContainerName="CarContext"
            EnableFlattening="False" EntitySetName="Cars" Select="it.[StudentId], it.[StudentName],it.[CourseName]">
        </asp:EntityDataSource>

and also edit the query of your EntityDataSource1, include CourseName to your query


text:
Q: MySQL keeps dying for no apparent reason I'm looking after a VPS with the following specifications: Centos 6, 50GB HDD & 512MB memory.
The problem I'm having is MySQL keeps on crashing for no apparent reason. I've double checked the log files and here's what I'm seeing:
Version: '5.1.71'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  Source distribution
140217 15:12:40 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
140217 15:12:40 [Warning] option 'thread_stack': unsigned value 65536 adjusted to 131072
140217 15:12:40  InnoDB: Initializing buffer pool, size = 8.0M
140217 15:12:40  InnoDB: Completed initialization of buffer pool
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
140217 15:12:40  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
140217 15:12:41  InnoDB: Started; log sequence number 0 1613784
140217 15:12:41 [Note] Event Scheduler: Loaded 0 events
140217 15:12:41 [Note] /usr/libexec/mysqld: ready for connections.
Version: '5.1.71'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  Source distribution

When I go to reboot the service, it returns "Another MySQL daemon already running with the same unix socket.". To get around this I've simply been renaming/removing the sock file. The MySQL server starts up but within a few hours or days it crashes again.
Any recommendations on how to debug or resolve this issue? Could it be related to memory usage?


text:
Q: Expected winnings from a game where I accept the money randomly drawn from the interval 0 to 100 if the proposed amount is more than 50 dollars I am trying to solve this probability puzzle: https://math.stackexchange.com/questions/1977360/expected-value-from-a-game-which-gives-random-numbers-from-1-to-100-with-reducin#:~:text=%22In%20front%20of%20you%20is,a%20new%20proposal%20next%20period.
The puzzle is:
"In front of you is an infinitely-lived machine that proposes amounts of money, which you can either accept or reject. If you accept, the machine hands over the proposed amount, but shuts down and will never give you anything else. If you reject, it'll show you a new proposal next period. Each period's proposal is an independent draw from a uniform distribution on [0, 100]. The time between periods is long — several months, say — and you are impatient: a dollar next period is worth only 0.9 to you today; similarly, a dollar two periods from now is worth 0.9*0.9 = 0.81 today, et cetera. If your strategy were to always accept, you'd expect to make 50 dollars, i.e. the mean of the first draw. If instead you decided to accept any first proposal above 50, and — in case you reject the first — any second proposal whatsoever, your expected discounted payoff would be 60 dollars. But you can do better! If you follow the strategy that maximizes your expected discounted payoff, what is the threshold above which you should accept the machine's first proposal?"
For a start, I am trying to calculate the expected winnings if I choose the threshold to be 50 dollars. I understood the solution mentioned in the above link but I came up with another approach which does not give the correct value when the threshold is 50 dollars. As per the question, for this threshold, the expected discounted payoff will be 60 dollars. But as per the formula derived in the solution, it comes out to be 68.18 dollars.
$$ V = \frac{(50000-5t^2)}{(1000-9t)} = 68.18, \text{for } t = 50$$.
Does the question contain the wrong value?
Now here is my approach:
Let $U_1, U_2, ... , U_N$ be i.i.d. drawn from $U(0,100)$ distribution. Here N is a random variable following geometric distribution with p = 0.5 i.e. N is the first period where we observe the proposed money to be more than 50 dollars. We then need to find $E[0.9^NU_N]$ i.e. the present value of our winnings. Now conditioning of N we can write,
$$E[0.9^NU_N] = E[E(0.9^NU_N|N)] = E[0.9^NE(U_N|N)] = 75E[0.9^N]$$
As 75 will be the expected value of $U_N$ if its more than 50 and less than 100. Now,
$$E[0.9^N] = \sum_{n=1}^\infty \frac{0.9^n}{2^n} = \frac{9}{11}$$
as $P(N = n) = 1/2^n$ i.e the probability of amount less than 50 in first $n-1$ draws and amount more than 50 in the $n^{th}$ draw. So the answer I get is 61.36 dollars which is incorrect. What is wrong with my solution?

A: If you accept the first offer when it is over $50$ then there is a probability of $\frac12$ of accepting an expected amount of $75$.
If you otherwise accept the second offer unconditionally then there is also a  probability of $\frac12$ of accepting an expected amount of $50$ next time but that is only worth $0.9\times 50=45$ now.  So the overall expected gain is $\frac{75}{2}+\frac{45}{2}=60$ as in the question.
But if you otherwise always accept later offers when they exceed $50$ then expected value now is $$\frac12\times 75 + \frac14 \times 0.9^1\times75  + \frac18 \times 0.9^2\times75+\cdots \\= \frac{75}{2}\sum_{n=0}^\infty \left(\frac{0.9}{2}\right)^2 \\=\frac{75}{2}\frac{1}{1-\frac{9}{20}} =\frac{750}{11} \approx 68.1818$$ as my formula in the linked answer suggested.


text:
Q: how to see all network requests made by an application Suppose i have an application running abc.exe, how to see all the network requests made by this application?
Wireshark is good to see all the requests from the pc, but is there any filter for requests from particular application.
The requests made by abc.exe can be of any type, http, https, or just LAN pings.
Is there any way to do it apart from seeing all network requests, just for an application.
For example: how we use charles for firefox, like that anything available?
Thanks.
EDIT: From using smartsniff i understood that we can't have single requests sent by an application.
Only browsers do that, send a request line and get a response. So most applications open an address and port & starts reading/writing from/into it.So how to trace them for an particular application?

A: You could try SmartSniff from NirSoft. This should give process information by enabling the 'Retrieve process information while capturing packets' option in the 'Advanced Options' window and then showing the relevant columns. See here for more details. Having said that, I couldn't get it to work, but you may have more luck.


text:
Q: Complexity of the algorithm that represnts the expression (n*(n-1)/2) For the equation : (n(n-1))/2
If you were to write an algorithm to represent this equation, what would be the complexity of such an algorithm?

A: Time complexity of (n*(n-1))/2 will be O(n^2).
This expression 1+2+3+4+...n-1 can be evaluated with O(n)  algorithm. And the time complexity of "resulting formula" need not always be the same(or linear). Big O notation can not be applied like that.
if a function is represented as (n*(n-1))/2 , it's rate of growth will not be linear. And Big O notation will talk about rate of growth of a function, so, the time complexity of (n*(n-1))/2 is O(n^2)
To be more specific, while calculating (n*(n-1)) for a larger value of n,  you have to store each and every digit of number in an array and after that multiply them. This will take O(N^2) time complexity where N is the number of digits.

A: (n*(n-1))/2  can be represented as (1 + 2 + ... + (n-1)). Finding the sum using this expanded expression would have O(n) time complexity and O(1) space complexity.
If you don't expand (n*(n-1))/2 into sum-expression, then it takes O(1) time complexity to do (n*(n-1))/2.
Why O(n) for expanded(sum) expression?
Since you are going to do the addition by considering (n-1) elements one by one.
So O(n) is considered same as O(n-1).


text:
Q: SonarQube MSBuild End Analysis Failure - Expected X to be a parent of Y I am encountering the following error on the SonarQube Scanner for MSBuild - End Analysis build task in Visual Studio Team Services.
2017-06-12T14:35:00.1131070Z SonarQube found 7 issues out of which 1 are new
2017-06-12T14:35:00.1131070Z
2017-06-12T14:35:00.1443593Z
2017-06-12T14:35:00.1599853Z ##[error]System.Management.Automation.RuntimeException: Internal Error: expected E:\\CI02\16\s to be a parent of E:\CI02\16\s\path\to\my\file.cs ---> System.Management.Automation.RuntimeException: Internal Error: expected E:\\CI02\16\s to be a parent of E:\CI02\16\s\path\to\my\file.cs
2017-06-12T14:35:00.1599853Z    --- End of inner exception stack trace ---
2017-06-12T14:35:00.1599853Z    at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
2017-06-12T14:35:00.1599853Z    at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace rs, Boolean performSyncInvoke)
2017-06-12T14:35:00.1599853Z    at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
2017-06-12T14:35:00.1599853Z    at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
2017-06-12T14:35:00.1599853Z    at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
2017-06-12T14:35:00.1599853Z    at Microsoft.TeamFoundation.DistributedTask.Handlers.LegacyVSTSPowerShellHost.VSTSPowerShellHost.Main(String[] args)
2017-06-12T14:35:00.1756102Z ##[error]LegacyVSTSPowerShellHost.exe completed with return code: -1.
2017-06-12T14:35:00.1756102Z ##[section]Finishing: Complete the SonarQube analysis

As you can see from the logs it is failing because E:\\CI02\16\s is not a parent of E:\CI02\16\s\path\to\my\file.cs (note the different number of backslashes after E:).
From looking at the build task's source code I can see that it is expecting the the file path to start with the value of the Build.Repository.LocalPath task context variable. I can't see why there is a difference in the number of slashes though.
This only occurrs when the build is triggered from a pull request. If I queue the build manually it succeeds without issue.
I am using version 2.1.2 of SonarQube for Team Services.
Does anyone know a way around this issue or have any suggestions?

A: The issue resolved itself. I retriggered the build from a pull request the next morning and it succeeded without issue.


text:
Q: How to migrate "attribute kind of directive" from angular1 to angular2? For example:
<input min="2" max="10" type="text" /> <!-- directive: min and max -->

Learning angular2 now, find it so amazing! But don't know a proper mapping in angular2 for attribute like directive in angular1.
Anybody willing to teach? Thx a ton!


text:
Q: Perforce : can I change the comment associated with a p4 integrate? Is it possible to change the comment associated with a p4 integrate after I have done the integrate? The integrate itself is fine but the comment associated with it needs improving.

A: You can edit any change (also submitted ones, at least for newer Perforce versions (at least 2009.2)) with
p4 -c <client-name> change <change-number>

Make sure $EDITOR is set.

A: If using P4V or P4Win, you can just select the submitted changelist, right click, & select 'Edit'.


text:
Q: Does $\lim\limits_{x \to 0}\frac{f(x)}x=0$ imply that $\lim\limits_{x \to 0}f(x)=0$? If I have the limit $\lim\limits_{x \to 0}\frac{f(x)}x=0$, does it mean that
$\lim\limits_{x \to 0}f(x)=0$?
I tried to use the definition of limit but unsuccessfully.

A: If $x \to 0$, then $x$ is close to zero, but it is not zero. So we can do: $$\lim_{x \to x_0} f(x) = \lim_{x \to x_0}\frac{f(x)}{x}x = \lim_{x \to x_0}\frac{f(x)}{x}\cdot \lim_{x \to x_0}x = 0 \cdot x_0 = 0.$$

A: Assume $\lim_{x\to0}f(x)$ exists.
If by contradiction $\lim_{x\to0}f(x)=a\neq0$ then $\lim_{x\to0}\frac{f(x)}{x}=\infty$.


text:
Q: How can you select into variable in PostgreSQL? I have the following function:
Create or Replace Function someFunction([parameter1], [parameter2]) Returns Integer As $$
Declare
    someInt_ integer;
    totalRows_ integer;
Begin
    SELECT x INTO someInt_, COUNT(*) INTO totalRows_
    FROM [table]
    WHERE [some conditions];

    [more code]
End;
$$ Language 'plpgsql';

The problem is that I get the following error:
ERROR:  «count» is not a known variable
LINE 6:  SELECT x INTO someInt_, COUNT(*) INTO totalRows_ ...
                                 ^
SQL state: 42601
Character: 181

How can I fix this?
I know a lot of data is missing, such as the return. It is because I have simplified it since the variables are in another language.

A: The INTO comes after all columns:
SELECT x, COUNT(*)
   INTO someInt_, totalRows_
FROM [table]
WHERE [some conditions];


text:
Q: PDFBox U+00A0 is not available in this font's encoding I am facing a problem when invoking the setValue method of a PDField and trying to set a value which contains special characters.
field.setValue("TEST-BY  (TEST)")

In detail, if my value contains characters as U+00A0 i am getting the following exception:

Caused by: java.lang.IllegalArgumentException: U+00A0 is not
  available in this font's encoding: WinAnsiEncoding

A complete stracktrace can be found here: Stacktrace
I currently have set PDType1Font.TIMES_ROMAN as font. In order to solve this problem i tried with other available fonts as well. The same problem persisted.
I found the following suggestion in this answer   https://stackoverflow.com/a/22274334/7434590 but since we use the setValue and not any of the methods showText/drawText that can manipulate bytes, i could not use this approach since setValue accepts only string as a parameter.
Note: I cannot replace the characters with others to solve this issue, i must be able to set any kind of supported by the font character in the setValue method.

A: You'll have to embed a font and not use WinAnsiEncoding:
PDFont formFont = PDType0Font.load(doc, new FileInputStream("c:/windows/fonts/somefont.ttf"), false); // check that the font has what you need; ARIALUNI.TTF is good but huge
PDResources res = acroForm.getDefaultResources(); // could be null, if so, then create it with the setter
String fontName = res.add(formFont).getName();
String defaultAppearanceString = "/" + fontName + " 0 Tf 0 g"; // adjust to replace existing font name
textField.setDefaultAppearance(defaultAppearanceString);

Note that this code must be ran before calling setValue().
More about this in the CreateSimpleFormWithEmbeddedFont.java example from the source code download.

A: Avoid using WinAnsiEncoding (problems with encoding)
PDDocument document = new PDDocument();

//Fonts
InputStream fontInputStreamAvenirMedium = new URL(Constants.S3 + "/Fonts/Avenir-Medium.ttf").openStream();
InputStream fontInputStreamAvenirBlack = new URL(Constants.S3 + "/Fonts/Avenir-Black.ttf").openStream();
InputStream fontInputStreamDINCondensedBold = new URL(Constants.S3 + "/Fonts/DINCondensedBold.ttf").openStream();

PDFont font = PDType0Font.load(document, fontInputStreamAvenirMedium);
PDFont fontBold = PDType0Font.load(document, fontInputStreamAvenirBlack);
PDFont fontDIN = PDType0Font.load(document, fontInputStreamDINCondensedBold);

//PDFont font = PDTrueTypeFont.load(document, fontInputStreamAvenirMedium, WinAnsiEncoding.INSTANCE); /* encoding problems  */
//PDFont fontBold = PDTrueTypeFont.load(document, fontInputStreamAvenirBlack, WinAnsiEncoding.INSTANCE); /* encoding problems  */
//PDFont fontDIN = PDTrueTypeFont.load(document, fontInputStreamDINCondensedBold, WinAnsiEncoding.INSTANCE); /* encoding problems  */

See also: https://pdfbox.apache.org/2.0/faq.html#fontencoding


text:
Q: Show modelless dialog initially hidden I have modelless child dialog. In resource properties Visible flag is set as true.(As per my requirement in resource properties visible flag should be true).
I want to  programmatically hide the dialog while initially displaying.
I overrided the presubclasswindow and removed the WS_VISIBLE flag using below code but the dialog is not getting hidden.
void CAddressChildDlg::PreSubclassWindow()
{
    CWnd::PreSubclassWindow();
    if (::IsWindow(m_hWnd))
    {
        LONG lStyle = GetWindowLong(m_hWnd, GWL_STYLE);
        lStyle &= ~WS_VISIBLE;
        SetWindowLong(m_hWnd, GWL_STYLE, lStyle);
    }
}

Please anyone help me to achieve my requirement

A: You can also override ON_WM_WINDOWPOSCHANGING
class CMyDialog : public CDialog
{
public:
    bool m_override_showwindow;
    //initialize somewhere ...

    void OnWindowPosChanging(WINDOWPOS* wpos)
    {
        if (m_override_showwindow)
            wpos->flags &= ~SWP_SHOWWINDOW;
        CDialog::OnWindowPosChanging(wpos);
    }
    DECLARE_MESSAGE_MAP()
    ...
};

BEGIN_MESSAGE_MAP(CMyDialog, CDialog)
    ON_WM_WINDOWPOSCHANGING()
    ...
END_MESSAGE_MAP()

Enable this override only when you don't want it to show the dialog. Make sure to disable the override otherwise dialog is never shown.
dlg.m_override_showwindow = true;
dlg.Create(...);
dlg.m_override_showwindow = false;

MessageBox(L"Test...");
dlg.ShowWindow(SW_SHOW);

A: You are not clear in what you want.  Your title says you want to initially have the dialog hidden.  then text in the question says you want it initially visible and then hidden.  Which is it/
What do you mean by your requirement says that the dialog style has to be WS_VISIBLE.  if you want to make it initially not visible, then don't include the flag.
For a modeless dialog, generally you create them on the heap whereas modal dialogs are typically created on the stack.
CYourDialog* pDlg = new CYourDialog(... and whatever arguments);
pDlg->Create(CYourDialog::IDD); // or whatever the ID is...
pDlg->ShowWindow(SW_NORMAL); // shows window if it was invisible...
pDlg->ShowWindow(SW_HIDE); // hides window if it was visible...


text:
Q: Do you really need to import 'React' when creating hooks? (React-hooks) I saw the examples where https://reactjs.org/docs/hooks-custom.html they always do:
import React, { useState, useEffect } from 'react';

But React is not really used in the file, do we really need it and why?
I asked this question because I am encountering an issue with eslint saying:
'React' is defined but never used  no-unused-vars - And I'm on create-react-app 3.0.1 which eslint is already included - (and I'm not sure how to fix this - already tried this and also tried adding it on package.json eslintConfig but still nothing)

A: You will need React if you are rendering JSX.
To avoid that eslint warning, you should use react-in-jsx-scope rule from eslint-plugin-react.
In that rule, it also explains why you need React in the file, even if you don't use it (you think you don't use it, but if you render JSX, you do).

When using JSX,  expands to React.createElement("a"). Therefore the React variable must be in scope.
  If you are using the @jsx pragma this rule will check the designated variable and not the React one.

A: React 17 has a new JSX transform which no longer requires the import (also backported to new versions 16.14.0, 15.7.0, and 0.14.10). You can read more about it here:
https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
// no import needed
const App = () =>
hello!

However, you still need to import to use hooks:
import { useState } from 'react'

const App = () => {
  const [stuff, setStuff] = useState('stuff')

  return
{stuff}

}

The docs also link to a script to automatically update all of the files in a project to fix all of the imports. Personally, I was in the habit of just using the React.useWhatever form so I never needed to mess with the import statement, but using named imports can potentially reduce the final bundle size.
The docs say the named import is now the recommended way, so this is NOT recommended, but if you really want to keep the React import, you can set the below eslint rule to stop it from complaining. Note that this will continue to require it in all files.
"react/jsx-uses-react": "error"

A: From the React official docs:

Fundamentally, JSX just provides syntactic sugar for the
  React.createElement(component, props, ...children) function. The JSX
  code:
<MyButton color="blue" shadowSize={2}>Click Me</MyButton>
compiles
  into:
React.createElement(MyButton, {color: 'blue', shadowSize: 2},'Click Me' )

You can also use the self-closing form of the tag if
  there are no children. So:

compiles into:
React.createElement('div', {className: 'sidebar'}, null )

https://reactjs.org/docs/jsx-in-depth.html
EDIT Hooks are also under the React namespace, React.useState ...etc


text:
Q: Formatting Slack messages sent from Errbot I'm sending a message to slack using subprocess.check_output. The format is a mess, I was thinking about trying markdown == false, but only want it set per module, and am not sure how to do that. I'm not sure if that will solve my issue though, the larger issue is how to format the following text to be readable
bad formatting
should look like (or close to):
clean formatting
Code:
@botcmd
def find_vm(self, args, SearchString):
    output = subprocess.check_output(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"C:\\Program Files\\Toolbox\\PowerShell Modules\\vmware\\./vmware.psm1\";", "find-vm", SearchString])
    return output

A: Wrap your output in triple-backticks, which denotes a code block in Markdown. Also make note you should decode the output of subprocess.check_output because it returns a stream of bytes, not "text" as we tend to think of it:
@botcmd
def find_vm(self, args, SearchString):
    output = subprocess.check_output(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"C:\\Program Files\\Toolbox\\PowerShell Modules\\vmware\\./vmware.psm1\";", "find-vm", SearchString])
    return "```\n{output}\n```".format(output=output.decode("utf-8"))

Be sure to replace utf-8 with the encoding your actual system is using.


text:
Q: Pulling text not enclosed in tags from a webpage I'm trying to crawl web pages and pull text from them using DOMDocument in PHP. Unfortunately, the HTML is difficult to work with. For example, it looks something like this:

    Link

    The text I need: 0613

I'm not sure how to pull out "The  text I need: 0613", since it's not enclosed in its own tag. Would regex be the best way to pull this out? I know that the format of the line will always be "The text I need: " followed by a four digit number.

A:
I know that the format of the line will always be "The text I need: " followed by a four digit number.

In that case you can probably use:
preg_match('/The text I need:\s*(\d+)/i', $str, $matches);

Your required number will be available in $matches[1].
PS: However for reliably parsing HTML page use DOM parsers.


text:
Q: How to Fix javax.imageio.IIOException: Can't read input file on Linux I am developing a small Gui Application and want to load my Images from the resource folder. This does work on Windows, but on Linux (Ubuntu 19.04 and Raspbian Buster) it does not.
I've been trying to switch from
getClass().getResource("black.jpg").getFile()

to
getClass().getClassLoader().getResource("black.jpg").getFile()

This is my View Class, extending from JFrame (shorted)
public View() {

        try {
            bI = ImageIO.read(new File(getClass().getClassLoader().getResource("black.jpg").getFile()));
        } catch (IOException e) {
            e.printStackTrace();
        }

[...]

contentPane = new BackgroundPanel(bI);

Error Message in terminal:
javax.imageio.IIOException: Can't read input file!
    at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
    at de.grapatin.escaperoom.view.View.<init>(View.java:38)
    at de.grapatin.escaperoom.controller.Controller.<init
(Controller.java:11)
    at de.grapatin.escaperoom.App.main(App.java:11)

I expect the image to be shown, but it does not happen. The background is black (like the image black.jpg in my code) but exchanging it does not solve the problem.
Project Structure:
─src
│   ├───main
│   │   ├───java
│   │   │   └───de
│   │   │       └───marvin
│   │   │           └───uitest
│   │   │               ├───controller
│   │   │               ├───model
│   │   │               │   └───enums
│   │   │               ├───util
│   │   │               └───view
│   │   └───resources
│   │       └───images

The output of
System.out.println(getClass().getResource("/black.jpg").getFile());

is
file:/C:/Users/marvin/uitest/target/uitest-0.0.1-SNAPSHOT.jar!/black.jpg

The ! does not come from my side
I just discovered that Windows does also not read from the Image File from the jar. But it is there in the root of the folder.
This question is not a duplicate of the following: imageio.IIOException: Can't read input file because the accepted Answer does not work in my case and the syntax is entirely different and against the accepted answer in my question. Also the edit does not clearly show how to adapt the solution.

A: Do not use the getFile() method of URL.  It does not return a valid file name.  It actually returns the path portion of a URL, with all percent-escapes intact.  It is named getFile because the URL class was part of Java 1.0, which was released in the mid 90s, back when nearly all URLs referred to physical files, either on the same computer or on a different computer.
Fortunately, you don't need it.  You can just use the read method of ImageIO which takes a URL:
bI = ImageIO.read(getClass().getResource("/images/black.jpg"));

An important benefit of treating resources as URLs, and never as Files, is that your code will work when you package your program in a .jar file.


text:
Q: Read files with Build Action = Content I have some files in my project that have Build Action set to Content.
How can I obtain a stream to read these content files?
PS: Setting the Build Action to Resource and then reading the file via Application.GetResourceStream() is not an option.

A: You can see a full sample in the MSDN Code Gallery I posted recently, showing how to access files deployed along with the application by using the Application.GetResourceStream() method.

A: Items with Build Action of Content are included in the package (.xap) file and are accessible via a Uri. You still use Application.GetResourceStream() to get at a stream
var si = Application.GetResourceStream(new Uri("FileName.ext", UriKind.Relative));
using (var sr = new StreamReader(si.Stream))
{
    //blah
}

This is fairly well documented in the MSDN help. Application.GetResourceStream


text:
Q: Why does property 'find' not exist on my array using // @ts-check on Javascript in VS Code? (2018, typescript 2.7x) ** update
console.log(Array.isArray(primaryNumberFemales)); // true

and I export it with:
export {
  primaryNumberFemales,
};

** end update
I have an array (which is of course type object) that looks like this:
const primaryNumberFemales = [{
  name: 'Sky',
  number: 6,
  duality: 'Yang',
  complexity: 'Complex',
  year: [1910,
    1919,
    1928,
    1937,
    1946,
    1955,
    1964,
    1973,
    1982,
    1991,
    2000,
    2009,
    2018,
  ],
},
{
  name: 'Lake',
  number: 7,
  duality: 'Yin',
  complexity: 'Simple',
  year: [1911,
    1920,
    1929,
    1938,
    1947,
    1956,
    1965,
    1974,
    1983,
    1992,
    2001,
    2010,
    2019,
  ],
},
];

Which I import with:
import {
  primaryNumberFemales,
} from './data';

and confirm it is an object after importing (so nothing funny has gone on somehow) with:
console.log(typeof primaryNumberFemales); // object

i want to type check my JS in VS Code 1.20.1 so add:
// @ts-check
now with the code below i get an error in the linter for every instance of find, the program works fine!:
  return (gender === 'F') ? {
    primaryNumber: (primaryNumberFemales.find(includesYearOfBirth) || {}).number,
    typeOfExpression: (primaryNumberFemales.find(includesYearOfBirth) || {}).name,
  } : {
    primaryNumber: (primaryNumberMales.find(includesYearOfBirth) || {}).number,
    typeOfExpression: (primaryNumberMales.find(includesYearOfBirth) || {}).name,
  };

Property 'find' does not exist on type '{ [x: string]: any; name: string; number: number; duality: string; complexity: string; year: numb...'.
I know Array.prototype.find() is es6, and it was not supported in the past (plenty of posts on that here before), but it should definitely be supported now. Is there something wrong with my code, or is this some kind of bug? THANKS!

A: If I parse the code in my head, when I'm looking at this expression:
import { primaryNumberFemales } from './data';

I'm wondering how the error isn't here, as your module doesn't export this constant. To fix this, I would use the export keyword:
export const primaryNumberFemales = [{
    name: 'Sky',
    number: 6,
    duality: 'Yang',
    complexity: 'Complex',
    year: [1910,
      1919,
      1928,
      1937,
      1946,
      1955,
      1964,
      1973,
      1982,
      1991,
      2000,
      2009,
      2018,
    ],
  },
  {
    name: 'Lake',
    number: 7,
    duality: 'Yin',
    complexity: 'Simple',
    year: [1911,
      1920,
      1929,
      1938,
      1947,
      1956,
      1965,
      1974,
      1983,
      1992,
      2001,
      2010,
      2019,
    ],
  },
  ];

If I run this example through the compiler it seems happy enough, I can use the Array.find method too. I have set my compiler to target ES6.


text:
Q: TheIntern - determining the environment for dynamic test generation I have a situation in which I need to dynamically generate functional tests.  Basically, I want to use BrowserStack to run my tests on a variety of different environments, but I want to register a different suite of tests depending on whether I'm running on desktop or mobile.
Here is a snippet of code from the file that kicks things off, so you can get an idea of how I'm going about it:
define(function (require) {
    var registerSuite = require('intern!object');
    var assert = require('intern/chai!assert');
    var config = require('intern/dojo/node!../../node_modules/our-repo/config');
    // RIGHT HERE I NEED TO KNOW PLATFORM + BROWSER INFO!
    var our_sites = ['A', 'C', 'C', 'D'];
    for (let i=0; i<our_sites.length; i++) {
        homepage_basic_site_test_suites(registerSuite, our_sites[i], config, assert);
    }
});

I then run through the config, dynamically generating tests and calling registerSuite.
What I would like is to be able to pass in one more parameter -- the environment that has been chosen.
https://theintern.io/leadfoot/module-leadfoot_Server.html#getSessionCapabilities Seems like it would provide the information I need, but I don't know how to get ahold of it.
My config for TheIntern includes the following list of environments, and I would like to know which one has been chosen for a particular run prior to calling the homepage_basic_site_test_suites() function:
environments: [
    {
        browserName: 'IE',
        version: ['11'],
        platform: ['WINDOWS']
    },
    {
        browserName: 'Edge',
        version: ['13', 'latest'],
        platform: ['WINDOWS']
    },
    {
        browserName: 'Firefox',
        version: ['54', 'latest'],
        platform: [ 'WINDOWS', 'MAC']
    },
    {
        browserName: 'Chrome',
        version: ['45', 'latest'],
        platform: ['WINDOWS', 'MAC']
    },
    {
        browserName: 'Safari',
        version: ['10.1', 'latest'],
        platform: 'MAC'
    },
    {
        browserName: 'iPhone',
        platform: 'MAC',
        device: ['iPhone 6'],
        realMobile: true
    },
    {
        browserName: 'iPad',
        platform: 'MAC',
        device: ['iPad 4th'],
        realMobile: true
    },
    {
        browserName: 'android',
        platform: 'ANDROID',
        device: ['Samsung Galaxy S5'],
        realMobile: true
    }
]

A: You can get environment information from the remote session. In a suite lifecycle method or a test, you would use this.remote.session.capabilities. However, the remote isn't available at the time registerSuite is called.
You could add tests within the suite itself, where the remote is available:
registerSuite({
    name: 'my suite',

    before: function () {
        if (this.remote.session.capabilities.something) {
            // Test is from intern/lib/Test
            this.tests.push(new Test({
                name: 'a test',
                parent: this,
                test: function () {
                    // test function
                }
            });
        }
    },

    ...
});

Another option would be to make remote-specific functional suites and load them using remote-specific configs. Like, have an Android config that loads android-specific functionalSuites, and an iOS config that loads iOS-specific functionalSuites. These configs can inherit from a central config, so that most properties will be shared.


text:
Q: Accessing external Spring config file from runnable jar Following is my directory structure
/app/infra/myjar/bin --> contains my runnable jar
/app/infra/myjar/config --> contains all external config files which I want to read from code which is inside jar.

Following is my code to read the external spring config file
ApplicationContext basicConfig =  new ClassPathXmlApplicationContext("classpath:/spring-bean-mapping.xml");

My MANIFEST file has following entry.
Class-Path:
.
../config/

Also I have set the CLASSPATH variable in my .bashrc to point to /app/infra/myjar/config folder
When I am trying to run the jar using
java -jar myjar.jar

I am getting following exception
Loading Spring Bean Mapping file
log4j:WARN No appenders could be found for logger        (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [spring-bean-mapping.xml]; nested exception is      java.io.FileNotFoundException: class path resource [spring-bean-mapping.xml] cannot be opened because it does not exist
    at  org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127)
    at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:451)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.vzw.esper.alerts.consumer.EsperMessagesConsumer.main(EsperMessagesConsumer.java:47)
Caused by: java.io.FileNotFoundException: class path resource [spring-bean-mapping.xml]  cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
    ... 13 more
Exception in thread "main" java.lang.NullPointerException
    at com.vzw.esper.alerts.consumer.EsperMessagesConsumer.main(EsperMessagesConsumer.java:86)

How can I understand what is going wrong here?

A: Fortunately I was able to resolve the above mentioned issue. The issue was when I was creating a Executable jar through Eclipse it was overriding my MANIFEST.MF class-path entries.
So after the jar has created I changed the MANIFEST.MF file to have desired entries and it worked.

A: I was able to resolve the 2nd issue where I was getting issue with spring component scanning.
I followed below spring forum link and it worked!!!
http://forum.spring.io/forum/spring-projects/container/89556-component-scanning-works-in-ide-but-not-in-an-executable-jar-file


text:
Q: Percentage in Reporting Services / Report Viewer I have a chart in a Report Viewer control:

Series data is a sum:

Problem How to make the Redemptions axis into a percentage?  eg 5am has 45% of the total redemptions for that day

A: without seeing your data, i'm going to guess that you'll probably have to do an aggregate of each day's Redemtpions, then join that to each time period.
so, without knowing your data or anything, here's an example:
 ;with dayavg as
(
    select day, count(*) as NumberRedemptionsDay
    from dbo.Redepmtions
    group by day
),
houravg as
(
    select day, hour, count(*) as NumberRedeptionsHour
    from dbo.Redemptions
    group by day, hour
)
select
    houravg.hour,
    houravg.NumberRedeptionsHour,
    (houravg.NumberRedeptionsHour/NumberRedemptionsDay)*100 as Perc
from houravg
    inner join dayavg
        on houravg.day=dayavg.day


text:
Q: Converting latitude in decimal degrees format to a hexadecimal value I have a latitude value in decimal degrees format (32.60601045). How would I go about converting it to a hexadecimal string?
I have a C# program that reads a hex string and decodes it into different fields. I know there is a latitude somewhere in the string whose value translates to 32.60601045, so I would like to convert the expected value of 32.60601045 into a hex string so I can locate it within my hexadecimal byte string.
EDIT:
Here is an example hex string:
02-00-62-E4-1B-C0-91-4D  40-40-AF-2D-29-64-D4-4A
5D-C0-00-66-66-6A-42-00  29-5C-8F-BD-00-00-63-00

A: The third to tenth hexadecimal pairs in your example contain the latitude in IEEE 754 format. It can be converted to double as follows:
long val=0x40404d91c01be462L;
double dbl=BitConverter.Int64BitsToDouble(val);
Console.WriteLine(dbl);

The latitude can be converted back to its "raw" bits as follows:
long latBits = BitConverter.DoubleToInt64Bits(dbl);


text:
Q: How to add arrows for left and right navigations in ant design angular tabs view in Angular?
I want to add left and right arrows to click tabs view. it's visible only 5 tabs more.
I used ant design new version(13.1..) it will show one dropdown I don't need dropdown.
how to solve it