unity – Call similar code more than once

I have the following code used by multiple classes (e.g. Enemy, Scenary, EnemyProjectile etc.) in my game, which seems intrinsically wrong. What are some ways I could write this code once and use it from multiple places?

        GameObject go = GameObject.Find("Player");
        if (go == null)
        {
            Debug.Log("Failed to find Player go");
        }
        else
        {
            _player = go.GetComponent<Player>();

            if (_player == null)
            {
                Debug.Log("Failed to find player component");
            }
        }

I usually have this code in an Awake function but sometimes I do it in a collision event, e.g. for EnemyProjectile grabbing a player handle would often not be required and thus a wasted lookup. Player is a private variable in the class definition of each class.

createrawtransaction – trouble posting a json-rpc call with vb.net

I’m trying to post to a local bitcoin full node via json-rpc but I’m getting nothing from the server.

Following the documentation here

My code works fine with getblockcount

like this:

  Private Sub button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click

        RichTextBox5.Text = RequestServer("getblockcount", New List(Of JToken))
    
   End Sub

But when i try to pass the call with params it returns nothing from the server

My code for the call with params:

 Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

       
        Dim s As JToken = "'({""txid"":""0000000000000000000000000000000000000000000000000000000000000000"",""vout"":0})'"
        Dim ss As JToken = "'{""bc1q5t4sexcufx9ecnepfd4v88j8fvq3q5ymzetmqt"":6.5}'"

        RichTextBox5.Text = RequestServer("createrawtransaction", New List(Of JToken) From {s, ss})
          End Sub

RequestServer Function:

 Public Shared Function RequestServer(ByVal methodName As String, ByVal parameters As List(Of JToken)) As JToken
        Dim ServerIp As String = "http://localhost:8332"
        Dim UserName As String = "hama"
        Dim Password As String = "hama"
        Dim webRequest As HttpWebRequest = CType(webRequest.Create(ServerIp), HttpWebRequest)
        webRequest.Credentials = New NetworkCredential(UserName, Password)

        webRequest.ContentType = "application/json-rpc"
        webRequest.Method = "POST"


        Dim respVal As String = String.Empty
        Dim joe As JObject = New JObject
        joe.Add(New JProperty("jsonrpc", 1))
        joe.Add(New JProperty("id", 1))
        joe.Add(New JProperty("method", methodName))
        Dim props As JArray = New JArray
        For Each parameter In parameters
            props.Add(parameter)
        Next
        joe.Add(New JProperty("params", props))
        ' serialize json for the request
        Dim s As String = JsonConvert.SerializeObject(joe)
        Dim byteArray() As Byte = Encoding.UTF8.GetBytes(s)
        webRequest.ContentLength = byteArray.Length
        Dim dataStream As Stream = webRequest.GetRequestStream
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()
        Dim streamReader As StreamReader = Nothing
        Try
            Dim webResponse As WebResponse = webRequest.GetResponse
            streamReader = New StreamReader(webResponse.GetResponseStream, True)
            respVal = streamReader.ReadToEnd
            Dim data = JsonConvert.DeserializeObject(respVal).ToString
            Return data
        Catch exp As Exception

        Finally
            If (Not (streamReader) Is Nothing) Then
                streamReader.Close()
            End If

        End Try

        Return String.Empty


    End Function

Help will be appreciated, thank you

Magento 2: Uncaught Error: Call to a member function setProduct() on boolean

I’m trying to update the product widget to show some custom product data like that

 <?= $block->getChildBlock('name-of-block')->setProduct($_item)->toHtml() ?>

while this code works fine on list.phtml in the CatalogWidget’s grid.phtml it cannot set the product

php – How to replace file_get_contents() with a WordPress Filesystem call

I’m using the PHP file_get_contents() function to retrieve and echo the contents of an SVG-file.

<?php echo file_get_contents( get_stylesheet_directory_uri() . '/assets/images/Search_Glyph.svg' ); ?>

I checked the theme with a theme checker and I am currently resolving all the issues. One of the issues is the use of file_get_contents.

It gives me the following warning:

WARNING: file_get_contents was found in the file header.php File operations should use the WP_Filesystem methods instead of direct PHP filesystem calls.

I tried finding information about the $wp_filesystem thing, but there is very little information available and even less examples (to be honest, I’m not totally sure if that’s the correct function to use).

How can I use a WordPress function to retrieve a file and echo the contents of it in a PHP-file?

I’m really at loss what I should do with this. All help is very much appreciated!

laravel – Call to a member function getRelationExistenceQuery() on null

el error se produce al intentar ejecutar los seeds.

este es el error detallado:

 at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php:49
45|         $method = $this->canUseExistsForExistenceCheck($operator, $count)
46|                         ? 'getRelationExistenceQuery'
47|                         : 'getRelationExistenceCountQuery';
48|

49| $hasQuery = $relation->{$method}(
50| $relation->getRelated()->newQueryWithoutRelationships(), $this
51| );
52|
53| // Next we will call any given callback as an “anonymous” scope so they can get the

  +3 vendor frames

4 database/factories/UserFactory.php:59
IlluminateDatabaseEloquentModel::__callStatic()

  +6 vendor frames

11 (internal):0
IlluminateDatabaseEloquentFactoryBuilder::IlluminateDatabaseEloquent{closure}()

esta es la factory:

use AppUser;
use AppCategory;
use AppProduct;
use AppTransaction;
use AppSeller;
use FakerGenerator as Faker;
use IlluminateSupportStr;

$factory->define(User::class, function (Faker $faker) {
    static $password;
    return (
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => Str::random(10),
        'verified' => $verificado = $faker->randomElement((User::USUARIO_VERIFICADO, User::USUARIO_NO_VERIFICADO)),
        'verification_token'=> $verificado == User::USUARIO_VERIFICADO ? null : User::generarVerificationToken(),
        'admin' => $faker->randomElement((User::USUARIO_ADMINISTRADOR, User::USUARIO_REGULAR)),
    );
});

$factory->define(Category::class, function (Faker $faker) {
    return (
        'name' => $faker->word,
        'description'=> $faker->paragraph(1),
    );
});

$factory->define(Product::class, function (Faker $faker) {
    return (
        'name' => $faker->name,
        'description'=> $faker->paragraph(1),
        'quantity'=> $faker->numberBetween(1, 10),
        'status'=> $faker->randomElement((Product::PRODUCTO_DISPONIBLE, Product::PRODUCTO_NO_DISPONIBLE)),
        'image'=> $faker->randomElement(('1.jgp', '2.jgp', '3.jgp')),
        'seller_id'=> User::all()->random()->id,
    );
});


$factory->define(Transaction::class, function (Faker $faker) {
    
    $vendedores= Seller::has('products')->get()->random();
    $comprador= User::all()->except($vendedores->id)->random();
    return (
        'quantity'=> $faker->numberBetween(1, 3),
        'buyer_id'=> $comprador->id,
        'product_id'=> $vendedores->products->random()->id,
    );
});

este es el seed:

use IlluminateDatabaseSeeder;
use AppUser;
use AppCategory;
use AppProduct;
use AppTransaction;

public function run()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        User::truncate();
        Product::truncate();
        Category::truncate();
        Transaction::truncate();
        DB::table('category_product')->truncate();

        $cantidadusuarios= 200;
        $cantidadcategorias= 30;
        $cantidadproductos= 1000;
        $cantidadtransacciones= 1000;

        factory(User:: class, $cantidadusuarios)->create();
        factory(Category:: class, $cantidadcategorias)->create();
        factory(Product:: class, $cantidadtransacciones)->create()->each(
            function($producto)
            {
                $categorias= Category::all()->random(mt_rand(1, 5))->pluck('id');
                $producto->categories()->attach($categorias->first());
            }
        );
        factory(Transaction:: class, $cantidadtransacciones)->create();

    }

sim card – How to call and SMS from Android smarphone with SIM via internet remotly?

I want to use my phone number when traveling abroad and there is no possibility to setup roaming, etc. So the idea is: I have Android smartphone. I have my SIM inserted in the phone. The phone works as usual phone – it is turned on and connected to charger. I need software that is capable to answer for incoming phone calls and relay the call via internet to some other phone or PC with corresponding software that runs on it. That is when somebody calls me, my phone that is turned on in my home answers to call, transfer the call/voice via internet to another country where I obtain some signal to my second phone or PC and can have a conversation. I have VOIP phone number but this doesn’t solve the issue – I need exactly the phone number bound to my physical SIM – some services verify that number is virtual and do not work with such numbers. Could you please suggest Android application that solve the issue.

c# – Call method by condition

I apologize in advance for my English.

I have a user search method. It’s parameters – login and strict. The last one determines, which method should have been used for search – Equals (strict is true) or Contains (strict is false). How should I implement it? I could do two different methods, but I think it would be code repeating.

    public async Task<List<UserFindInfoDTO>> FindUserByLoginAsync(string login, bool strict)
    {            
        var users = await context.Users
            .Where(u => u.Nickname.Equals(login)) // change on "Contains" if strict is false
            .Select(u => new UserFindInfoDTO
            {
                Status  = u.Status,
                Id = u.Id,
                MiniAvatar =  u.Image,
                Nickname = u.Nickname                    
            })
            .ToListAsync();
            ...
        return users;
    }

microsoft – Call WCF service from ASP.NET core 3.1 API

I am getting below error when I am trying to call WCF service from ASP.Net Core, this is happening only when both wcf service and API deployed on IIS 10.

Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) System.ServiceModel.CommunicationException: No connection could be made because the target machine actively refused it.
—> System.Net.Http.HttpRequestException: No connection could be made because the target machine actively refused it.
—> System.Net.Sockets.SocketException (10061): No connection could be made because the target machine actively refused it.
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)

I am able to connect same WCF service from ASP.NET MVC controller. It fails only when we access from .net core.

Any thoughts here, will be greatly apricated.

Thanks,
Pani

pnp – How can we call oneDrive data into SPFx webpart, which is hosted in SharePoint site?

Stack Exchange Network


Stack Exchange network consists of 177 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Is it possible to have duplicate transactions in "listsinceblock" RPC call ? If yes, why?

Is it possible to have duplicate transactions(same transactions in the response) in "listsinceblock" RPC call ? If yes, why?