text:
Q: How do I take an array of strings and separate them further into objects? I have an array of strings identifying a pet name, type of animal, age and their owner's name (each attribute is separated by a comma):
String[] petInfo = ["Spot, dog, 2, Joey", "Kip, dog, 3, Jack", "Snuffles, cat, 1, Jane" , "Franklin, turtle, 4, Arthur",...]

I created a pet class with members string petName, string type, int age and string ownerName.
public class Pet
{
string petName;
string type;
int age;
string ownerName;

//getters
}

In my main I declared
List<Pet> pets = new ArrayList<Pet>();

I want to create an array of pet objects using an arraylist. I know I have to use split to get through the original array but that leaves me with another array of comma separated values for one pet. How do I write a loop that can go through the petInfo array and add those values to each pet object in my list?

A: Here is all you need:
    import java.util.ArrayList;
    import java.util.List;

    public class Main {
        public static void main(String[] args) {
            String[] petInfo = {"Spot, dog, 2, Joey", "Kip, dog, 3, Jack", "Snuffles, cat, 1, Jane" , "Franklin, turtle, 4, Arthur"};
            List<Pet> pets = new ArrayList<Pet>();
            for (String singlePetInfo : petInfo) {
                pets.add(getPetFromString(singlePetInfo));
            }

            pets.forEach(System.out::println);
        }

        private static Pet getPetFromString(String petDescription){
            String[] split = petDescription.split(", ");
            return new Pet(split[0], split[1], Integer.parseInt(split[2]), split[3]);
        }
    }

A: A very verbose example: This method takes the array and converts the pet parts to a pet. Returning the list of pets at the end.
public List<Pet> toPets(String[] petArray) {
  List<Pet> pets = new ArrayList();
  for (String petAsString: petArray) {
     String[] petParts = petAsString.split(",");
     String petName = petParts[0].trim();
     String type = petParts[1].trim();
     int age = Integer.parseInt(petParts[2].trim());
     String ownerName = petParts[3].trim();
     Pet pet = new Pet(petName, type, age, ownerName);
     pets.add(pet);
  }
  return pets;
}

A: I wrote a solution. There are two key points. Splitting string can cause faulty solutions. That's why, I added a proper regex. Also you need to take care of integer conversion. Using integer class makes it easy for you.
    String[] petInfo = {"Spot, dog, 2, Joey", "Kip, dog, 3, Jack", "Snuffles, cat, 1, Jane" , "Franklin, turtle, 4, Arthur"};
    List<Pet> pets = new ArrayList<Pet>();

    for (int i = 0; i < petInfo.length; i++) {
        String[] pet = petInfo[i].split("\\s*,\\s*");
        pets.add(new Pet(pet[0], pet[1], Integer.parseInt(pet[2]), pet[3]));
    }

A: You can create a Constructor or helper method to create Pet object from given string.
Following is code snippet for constructor. See here the complete working code:
Pet(String val)
{
    String[] vals = val.trim().split(",");
    petName = vals[0].trim();
    type = vals[1].trim();
    age = Integer.valueOf(vals[2].trim());
    ownerName = vals[3].trim();
}

To use it, you can do something like following:
    String[] petInfo = new String[]{"Spot, dog, 2, Joey",
        "Kip, dog, 3, Jack", "Snuffles, cat, 1, Jane" , "Franklin, turtle, 4, Arthur"};
    ArrayList<Pet> list = new ArrayList();
    for(String p:petInfo)
    {
        list.add(new Pet(p));
    }

A: Take your petInfo array and go through it with a for loop. Then you split your string and create a new Pet object, then you can just add it to your List<Pet> called pets
List<Pet> pets = new ArrayList<Pet>();

//Renamed it to petInfos, for better usage in the for loop
String[] petInfos = ["Spot, dog, 2, Joey", "Kip, dog, 3, Jack", "Snuffles, cat, 1, Jane" ,
    "Franklin, turtle, 4, Arthur",...]

for(String petInfo : petInfos){
   String[] petInfoSplitted = petInfo.split(", ");

   pets.add(new Pet(petInfoSplitted[0], petInfoSplitted[1],
       Integer.parseInt(petInfoSplitted[2]), petInfoSplitted[3]);
}

I hope my awnser was helpfull.


text:
Q: Check if all the positive values from an array are consecutive https://www.geeksforgeeks.org/maximum-consecutive-ones-or-zeros-in-a-binary-array/
Does anyone have an idea how to modify this code so that it returns if all positive values (1) are consecutive?
Basically, I don't want the counter that tells me the maximum number of 1 consecutive, I want to return if absolutely all are consecutive, so in case all are consecutive, the answer would be true, otherwise it would be false.
In the example: arr = [1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1] it would return false cause there are 0 between the 1, not all are consecutive BUT in this = arr = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1] it would return true cause all the 1 are consecutive.
I didn't try anything cause I don't know how to start, maybe with a combination of booleans?. I'm working with python just in case!
Thank you all!

A: You can do this pretty easily with numpy .  Taking the difference between successive elements will leave you with zeros where neighbors are equal, +1 where the neighbor increases (like 1 to the right of 0) and negative where the neighbor decreases. So the following works, also for numbers other than 0,1:
import numpy as np
z=np.array([0,0,0,0,1,1,1,1,1,2,3])
all(np.diff(z)>=0)

Out[9]: True

z=np.array([0,0,0,0,1,1,1,1,1,2,1])
all(np.diff(z)>=0)

Out[11]: False

A: This feels like a homework question so I won't give you the code but here's some pseudocode.
This is by no means efficient but is quite intuitive
tracker = []
arr = [0, 0, 0, 12, 12, 12, 11, 10]
iterating through every index, keep track of how many times that number has come up

*

*if the number has never been seen before

*

*set that index to 1 ie. tracker[index] = 1

*if it has been seen before

*

*increment tracker[index] by 1

*check if
arr[index-1] equals arr[index]

*

*if it does not, then its not
consecutive

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jersey 2.7 + GlassFish 4 CDI deployment failure I'm trying to learn Java specifically in making a RESTful Web Service.
I'm using Intellij IDEA 13 as IDE, GlassFish 4.0 as server and Jersey 2.7.
Here is the screenshot of the project's structure:

When I tried to deploy the project, it always fails with a sort of dependency injection exception.
GlassFish's log :
[2014-03-27T11:46:36.443+0700] [glassfish 4.0] [SEVERE] [NCLS-CORE-00026] [javax.enterprise.system.core] [tid: _ThreadID=33 _ThreadName=admin-listener(2)] [timeMillis: 1395895596443] [levelValue: 1000] [[
  Exception during lifecycle processing
org.glassfish.deployment.common.DeploymentException: CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [IterableProvider<InjectionResolver<Object>>] with qualifiers [@Default] at injection point [[BackedAnnotatedParameter] Parameter 2 of [BackedAnnotatedConstructor] @Inject org.glassfish.jersey.internal.inject.JerseyClassAnalyzer(@Named ClassAnalyzer, IterableProvider<InjectionResolver<Object>>)]
    at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:225)
    at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
    at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:328)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:493)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:356)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [IterableProvider<InjectionResolver<Object>>] with qualifiers [@Default] at injection point [[BackedAnnotatedParameter] Parameter 2 of [BackedAnnotatedConstructor] @Inject org.glassfish.jersey.internal.inject.JerseyClassAnalyzer(@Named ClassAnalyzer, IterableProvider<InjectionResolver<Object>>)]
    at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:403)
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:325)
    at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:177)
    at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:208)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:519)
    at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:505)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:480)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:536)
    at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:216)
    ... 36 more
]]

[2014-03-27T11:46:36.444+0700] [glassfish 4.0] [SEVERE] [] [javax.enterprise.system.core] [tid: _ThreadID=33 _ThreadName=admin-listener(2)] [timeMillis: 1395895596444] [levelValue: 1000] [[
  Exception while loading the app]]

[2014-03-27T11:46:36.444+0700] [glassfish 4.0] [SEVERE] [AS-WEB-GLUE-00192] [javax.enterprise.web] [tid: _ThreadID=33 _ThreadName=admin-listener(2)] [timeMillis: 1395895596444] [levelValue: 1000] [[
  Undeployment failed for context /VisiJobs_war_exploded]]

[2014-03-27T11:46:36.450+0700] [glassfish 4.0] [SEVERE] [] [javax.enterprise.system.core] [tid: _ThreadID=33 _ThreadName=admin-listener(2)] [timeMillis: 1395895596450] [levelValue: 1000] [[
  Exception while loading the app : CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [IterableProvider<InjectionResolver<Object>>] with qualifiers [@Default] at injection point [[BackedAnnotatedParameter] Parameter 2 of [BackedAnnotatedConstructor] @Inject org.glassfish.jersey.internal.inject.JerseyClassAnalyzer(@Named ClassAnalyzer, IterableProvider<InjectionResolver<Object>>)]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [IterableProvider<InjectionResolver<Object>>] with qualifiers [@Default] at injection point [[BackedAnnotatedParameter] Parameter 2 of [BackedAnnotatedConstructor] @Inject org.glassfish.jersey.internal.inject.JerseyClassAnalyzer(@Named ClassAnalyzer, IterableProvider<InjectionResolver<Object>>)]
    at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:403)
    at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:325)
    at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:177)
    at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:208)
    at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:519)
    at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:505)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:480)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:536)
    at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:216)
    at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
    at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:328)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:493)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:356)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
    at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
    at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
]]

Need advice on this.
Thanks !

A: Missing org.glassfish.hk2.api library.


text:
Q: How to replace the content in webpage in Google Chrome extension every 5 seconds? I am writing a simple chrome extension which should replace the particular content of the webpage every 5 seconds?
Whether it's possible to anything like that?
This is my function (This would replace particular content)
replaceText(document.body.innerHTML);

How to run this function every x seconds in my script 'myscript.js'?

A: The simplest way would be to use setTimeout. It will look something like this:
function timedFunction() {
    replaceText(document.body.innerHTML);
    setTimeout("timedFunction()",5000);
}

timedFunction();

A: You could use setTimeout().
See w3schools timing events reference.


text:
Q: how to upload file to azure blob with original file name using Fine Uploader I'm uploading a file named my-image.jpg into my blob container with the endpoint of https://myaccount.blob.core.windows.net/my-container on Azure.
After than it calls signature endpoint for SaS token and generate PUT request to Azure blob. Here i observed that PUT request does not contain original file name instead of that some GUID replaced file name.
I  want my original file name to be there in the PUT request so that the file will be uploaded on blob with the original name.
Would then https://myaccount.blob.core.windows.net/my-container/89056c3d-7bb3-my-image.jpg be the bloburi I send to my API while requesting a SAAS?
How do i achieve this ?
When my request hits my backend API to get a SAS, the blobUri comes in as /server/upload/some-guid-value.txt. I'm using the following options when instantiating an uploader. What am I doing wrong?
const uploader = new qq.azure.FineUploader({
        element: document.getElementById('fine-uploader-manual-trigger'),
        template: 'qq-template-manual-trigger',
        request: {
            endpoint: 'https://myaccount.blob.core.windows.net/my-container',

        },
        signature: {
            endpoint: 'http://localhost:4879/api/getsas',
            cors:{
                expected: true,
                sendCredentials: false
            },
        }
})

A: By default, File Uploader azure will use a UUID to name your object. In almost cases, this is the safest behavior.
If you change this value, you will run the risk of overwriting existing files with new ones in the event of a name collision.
If you must save the blob in azure using a different name, you could modify the blobProperties.name option appropriately.
A value of "filename" will save the object using the original filename.
For more detail, you could read about this option.


text:
Q: How can I create an object that contains instances of a class in Python? I want to create an object that contains some instances of a class. That object should be some kind of list-generalization of the instances. E.g. I have the following class:
class car:
    def __init__(self, prize, color)
        self.prize = prize
        self.color = color

Now I want to have an object cars that contains many instances of the class car but that I can work with like an instance of car, i.e. cars.prize should return a list of the prizes for all the instances I collected in that object cars.

A: I think you can do something like that:
class Cars:
    def __init__(self, list_of_cars):
        self.cars_list = list_of_cars
        self.prize = [car.prize for car in self.cars_list]
        self.color = [car.color for car in self.cars_list]

Let's see how it can be used:
list_of_cars = [Car(1000, "red"), Car(2000, "blue"), Car(3000, "Green")]
x = Cars(list_of_cars)

print(x.prize)
# [1000, 2000, 3000]

print(x.color)
#["red", "blue", "Green"]

A: You could create a new class car_list() that holds a list of cars (to which you can append, remove etc). In that class, add aget_prizes() method that returns a list of prizes by iterating over the list. For example:
class car_list():
   def __init__(self, cars):
      self.cars = cars # This is a list

   def get_prizes(self):
      return [car.prize for car in self.cars]

A: Small error in your code: you need a : at the end of your __init__ method definition line:
def __init__(self, prize, color):
Here's an implementation of cars which does what you desire. The use of the @property decorator allows you to access methods as object properties:
class car:
    def __init__(self, prize, color):
        self.prize = prize
        self.color = color

class cars:
    def __init__(self, list_of_cars):
        for one_car in list_of_cars:
            assert isinstance(one_car, car) # ensure you are only given cars
        self.my_cars = list_of_cars

    @property
    def prize(self):
        return [one_car.prize for one_car in self.my_cars]

    @property
    def color(self):
        return [one_car.color for one_car in self.my_cars]

>>> a = car('prize1', 'red')
>>> b = car('prize2', 'green')
>>> c = car('prize3', 'azure')
>>> carz = cars([a,b,c])
>>> carz.prize
['prize1', 'prize2', 'prize3']
>>> carz.color
['red', 'green', 'azure']

You can add more checking on inputs in each object if desired, but this is the basic framework. Hope it helps, Happy Coding!

A: This answer is inspired by the wonderful Sam idea of using decorators. So please give him the point if you think you are pleased with this chunk of code.
def singleton(all_cars):
    instances = {} # cars instances
    def get_instance():
        if all_cars not in instances:
            # all_cars is created once
            instances[all_cars] = all_cars()
        return instances[all_cars]
    return get_instance

@singleton
class all_cars:
    def __init__(self):
        self.inventory = {}

    @property
    def prizes(self):
        return [e.prize for e in self.inventory.values()]
    @property
    def colors(self):
        return [e.color for e in self.inventory.values()]

class car:
    def __init__(self, prize, color):
        self.prize = prize
        self.color = color

    def register(self):
        # Like class all_cars is a singleton it is instantiate once, reason why dict is saved
        cars = all_cars()
        cars.inventory[len(cars.inventory)] = self

if __name__ == '__main__':
    # Creating cars items
    car1 = car("50", "Blue")
    car2 = car("300", "Red")
    car3 = car("150", "Gray")
    # Register part for cars
    car1.register()
    car2.register()
    car3.register()
    # Like class all_cars is a singleton it is instantiate once, reason why dict is saved
    cars = all_cars()

    print(cars.inventory)
    """{0: <__main__.car object at 0x7f3dbc469400>, ---> This is object car1
    1: <__main__.car object at 0x7f3dbc469518>,  ---> This is object car2
    2: <__main__.car object at 0x7f3dbc469550>}  ---> This is object car3"""
    print(cars.prizes)
    """['50', '300', '150']"""
    print(cars.colors)
    """['Blue', 'Red', 'Gray']"""


text:
Q: MongoMapper: Get all models Does anyone know of an easy way to fetch the class names of all models that have MongoMapper::Document included?
The MongoMapper class doesn't appear to have the equivalent of ActiveRecord::Base.subclasses.
The best I can come up with is using MongoMapper.database.collection_names and some ObjectSpace hacks.
A further complication is that I have modules (subfolders) in the app/models folder. So, class DS::Thingy is in my apps/models/ds/thingy.rb.

A: How about something like:
class MongoModels
  def self.all
    @@models ||= []
  end
end

module MongoMapper
  module Document
    def self.included(klass)
      MongoModels.all << klass
    end
  end
end

then MongoModels::all would return an Array of models.
MongoMapper's document.rb does:
included do
  extend Plugins
  extend Translation
end

So you might need to replicate that.


text:
Q: Custom price of product not getting applied in cart in Magento 2 I am trying to set the custom price of product to cart using Magento2 but unable to do that. For that I have created a module TW - as namespace Cart- as Module name . So under TW/Cart I have created 2 folders etc and Observer. Below is the code in respective folders. Do i need to register this module by putting registration.php file under this module ? Please help me what am I doing wrong?
Code for etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
        <observer name="cart_observer_customprice" instance="TW\Cart\Observer\CustomPrice" />
    </event>
</config>

Code for Observer/CustomPrice.php
namespace TW\Cart\Observer;
 use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Psr\Log\LoggerInterface;

class CustomPrice implements ObserverInterface
{
    protected $logger;
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
    public function execute(\Magento\Framework\Event\Observer $observer) {

        $item = $observer->getEvent()->getData('quote_item');
        $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
        $price = 120; //set your price here
        $this->logger->debug("Hello I am here", [
            'price' => $price,
        ]);
        $item->setCustomPrice($price);
        $item->setOriginalCustomPrice($price);
        $item->getProduct()->setIsSuperMode(true);
    }

}

A:
First create a module using free module creator tool called silk software

 Magento 2 Module Creator Tool Using Silk Software
and enable using following commands below.

*

*php bin/magento module:enable Tw_Cart

*php bin/magento setup:upgrade

*php bin/magento setup:di:compile

*php bin/magento setup:static-content:deploy

create events.xml in the path:- app/code/Tw/Cart/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_cart_product_add_after">
        <observer name="Tw_Cart_Addtocart_Customprice" instance="TW\Cart\Observer\CustomPrice" />
    </event>
</config>

create CustomPrice.php in the path: app/code/Tw/Cart/Observer/ & keep the below code

<?php
    namespace TW\Cart\Observer;
    use Magento\Framework\Event\ObserverInterface;
    use Magento\Framework\App\RequestInterface;
    use Psr\Log\LoggerInterface;
    class CustomPrice implements ObserverInterface
    {

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
            $writer = new \Zend\Log\Writer\Stream(BP.'/var/log/stackexchange.log');
            $logger = new \Zend\Log\Logger();
            $logger->addWriter($writer);
            /* Code here */
            $quote_item = $observer->getEvent()->getQuoteItem();
            $price = 400; //set your price here
            $quote_item->setCustomPrice($price);
            $quote_item->setOriginalCustomPrice($price);
            $quote_item->getProduct()->setIsSuperMode(true);
            $logger->info("success !!!!");
    }

}


text:
Q: Blast Particle Not Spreading to Fullscreen I want to create a blast into the whole screen and spread a wave kind of effect into my 2d game. But the blast particle effect not expanding the camera window and I have captured a screenshot at the right time to explain my problem properly.

As you are seeing, the particle-wave blast actually crosses the screen or camera area but in the actual game window, I can't able to see the same effect.
It gets limited the expansion within the same window.
Here is the particle settings that I have set:

Now I can't able to understand exactly what problem exists so please guide me into this.


text:
Q: Opening Spotify app from my reactnative/expo app I would like to open Spotify from inside my react-native (expo) app. I currently use WebBrowser; which opens up, unsurprisingly, a new browser, displaying the playlist.
Has anyone found a simple way of launching the Spotify app from within Expo/RctNtv?
 _handlePressButtonAsync = async () => {
    let result = await WebBrowser.openBrowserAsync('http://open.spotify.com/playlist/{id});
    this.setState({ result });
  };

<Button
          style={styles.paragraph}
          title="Open Spotify"
          onPress={this._handlePressButtonAsync}
        />

Thanks


text:
Q: Return column headers based on value in table I have a table that has both column headers and row titles. Each cell in the matrix can be empty or not. The actual value is inconsequential. My goal is to look at each row by title and return an array of column headers for which the intersecting cell is not empty.
Titles    Col_A    Col_B    Col_C    ...
Row_1                x
Row_2       x                 x
Row_3       x

If interested in Row_1, I should return {Col_B}, or if searching Row_2 then I should return {Col_A, Col_C}.
I have the following formula that return an array of cell values for non-empty cells, but I do not know how to get the column headers from this.
=FILTER(XLOOKUP(A2,OtherSheet!A:A,OtherSheet!B:O,""),NOT(ISBLANK(XLOOKUP(A2,OtherSheet!A:A,OtherSheet!B:O,""))))

So using the above example, if A2=Row_1, the formula above would return {x}, or if A2=Row_2, {x,x}.
Because I know this table is limited to single values ("FOO") I have also tried the formula
XLOOKUP("FOO",XLOOKUP(A2,OtherSheet!$A$1:$A$31,OtherSheet!B$2:$O$32),OtherSheet!B$1:$O$1)

Which for A2=Row_2 returns Col_A alone rather than an array of all matching values.
If I give the outer XLOOKUP as the first parameter an array ({"FOO","FOO",...}) it simply returns the same length array with all values being Col_A.

A: Here is the way:-
=FILTER(B1:D1,ISBLANK(INDEX(B2:D4,MATCH("Row_2",A2:A4,0),0))=FALSE,FALSE)

The formula is tested on your sample and shows the way to construct a solution. I think you'll be able to make the final adjustments. However, I had a little trouble with it from which I learned that the number of columns in the INDEX and the FILTER must be identical.

A: This formula returns not an array, but a comma separated list of titles. The text value in the grid can be anything.

=TEXTJOIN(",",TRUE,IF(ISBLANK(INDEX(B2:B6,MATCH(F2,$A$2:$A$6,0)):INDEX($D$2:$D$6,MATCH(F2,$A$2:$A$6,0))),"",$B$1:$D$1))


text:
Q: Model validation is Not working for the derived classes. even though i have mentioned the known types I am using asp.net core 2.2 and model validation for server side validation.
Its working fine except for known types.
this is my class structure
    //Main Class

    [DataContract]
    [KnownType(typeof(SubClass2))]
    [KnownType(typeof(SubClass1))]
    public partial class MainCass : Base
    {
    //properties comes here
    }

    //Sub Classes

    [DataContract]
    public partial class SubClass1 : MainCass
    {
    //properties comes here
    }

    [DataContract]
    public partial class SubClass2 : MainCass
    {

    [DataMember]
    [CustomRequired(ErrorMessageResourceType = typeof(ErrorMessages),
    ErrorMessageResourceName = "FieldRequired", Caption = "name required")]
    public string Name  {get; set; }

    }

//this is my request model
    [DataContract]
    public partial class request:Base
    {
    [DataMember]
    public List<MainCass> MainCassList  {get; set; }
    }

now the validation attribute of Name in SubClass2 is not getting called.
From UI I am sending type Subclass2.

A: The model binder does not support polymorphism. It creates the literal type(s) of the model and any related sub-models. Then, it attempts to bind the request body to these types. It will not infer derived types.
In other words, it sounds like you're sending instances of SubClass1 and SubClass2 as part of your MainClassList property. However, the model binder is going to create all of these as MainClass because that's the type that's defined. Any posted data specific to SubClass1 or SubClass2 will simply be discarded, and in the end, all you have is instances of MainClass. As such, of course no specific validation on SubClass1 or SubClass2 is being run, because you have no instances of SubClass1 or SubClass2.


text:
Q: txt file to string to array into mysqli db with php UPDATED2
I have a txt file(output.txt) generated that looks like this, but there are varying numbers of arrays of doorGroups
{"DGGroups"[{"DoorGroupID":"1","DoorGroupName":"Default","DoorGroupStatus":"Lock"}{"DoorGroupID":"2","DoorGroupName":"Group 1","DoorGroupStatus":"Unlock"}{"DoorGroupID":"3","DoorGroupName":"Group 2","DoorGroupStatus":"Lock"{"DoorGroupID":"4","DoorGroupName":"Group 3","DoorGroupStatus":"Unlock"}{"DoorGroupID":"5","DoorGroupName":"Group 4","DoorGroupStatus":"Lock"}]}

I need to be able to rip through the file and insert the values into the mysqli db that has corresponding columns
    id  doorGroupID     doorGroupName   doorGroupStatus

This is the non working code i have at the moment - I have tried many variations. I cut out some things on the string to make it better to work with. Calling jsondecode still returns NULL. I have it operating on a button press. Any direction will be appreciated.
//Forms posted
if (isset($_POST['submit']))
{

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
 //read the  file contents
$data = file_get_contents('output.txt');
var_dump($data);
echo "
";
echo "
";

$data = substr($data, 13, strlen($data) - 17); // remove outer ( and )
$data = str_replace('"', "", $data);
$data = str_replace('{', "", $data);
$data = str_replace('}', "|", $data);
var_dump($data);

echo "
";
echo "
";

$output = json_decode($data, true);
echo "
";
var_dump($output);

$ret = array_map (
  function ($_) {return explode (',', $_);},
  explode ('|', $data)
);

print_r ($ret);

    //insert into mysql table
    $sql = "INSERT INTO doorGroups(doorGroupID, doorGroupName, doorGroupStatus)
    VALUES('$DoorGroupID', '$DoorGroupName', '$DoorGroupStatus')";

   if ($conn->query($sql) === TRUE) {
    echo "
updated successfully
";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();

}

?>

<form  method='post'>

      <form class='form-horizontal'>

      </form>

        <button type='submit' name='submit' class='btn btn-primary center-block'>Do It</button>

  </form>

the file outputs to this
    string(371) "{"DGGroups"[{"DoorGroupID":"1","DoorGroupName":"Default","DoorGroupStatus":"Lock"}{"DoorGroupID":"2","DoorGroupName":"Group 1","DoorGroupStatus":"Unlock"}{"DoorGroupID":"3","DoorGroupName":"Group 2","DoorGroupStatus":"Lock"}{"DoorGroupID":"4","DoorGroupName":"Group 3","DoorGroupStatus":"Unlock"}{"DoorGroupID":"5","DoorGroupName":"Group 4","DoorGroupStatus":"unLock"}]} "

string(290) "DoorGroupID:1,DoorGroupName:Default,DoorGroupStatus:Lock|DoorGroupID:2,DoorGroupName:Group 1,DoorGroupStatus:Unlock|DoorGroupID:3,DoorGroupName:Group 2,DoorGroupStatus:Lock|DoorGroupID:4,DoorGroupName:Group 3,DoorGroupStatus:Unlock|DoorGroupID:5,DoorGroupName:Group 4,DoorGroupStatus:unLock"

NULL
Array
(
    [0] => Array
        (
            [0] => DoorGroupID:1
            [1] => DoorGroupName:Default
            [2] => DoorGroupStatus:Lock
        )

    [1] => Array
        (
            [0] => DoorGroupID:2
            [1] => DoorGroupName:Group 1
            [2] => DoorGroupStatus:Unlock
        )

    [2] => Array
        (
            [0] => DoorGroupID:3
            [1] => DoorGroupName:Group 2
            [2] => DoorGroupStatus:Lock
        )

    [3] => Array
        (
            [0] => DoorGroupID:4
            [1] => DoorGroupName:Group 3
            [2] => DoorGroupStatus:Unlock
        )

    [4] => Array
        (
            [0] => DoorGroupID:5
            [1] => DoorGroupName:Group 4
            [2] => DoorGroupStatus:unLock
        )

)
updated successfully

So basically now the hangup is i can get the string to explode to the right groups but i cant access the value pairs.  It is a group of value pair groups.  How do i break it down so that i have the info in the same groups and access to the corresponding information?

A: This is a bastardized version of JSON, but I think it can be beaten into submission with regular expressions. (Yes, I know, now I have two problems...)
As well, you absolutely do not want to be dumping external data into your database without safeguards. You may think it's trustworthy because it comes from another server in your organization, but it's not. Prepared statements give you protection and also greatly reduce the overhead needed to get this stuff into the database.
<?php
#set up the database stuff
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "INSERT INTO doorGroups(doorGroupID, doorGroupName, doorGroupStatus)
VALUES(?,?,?)";
$stmt = $conn->prepare($sql);

# the data; one missing } was added from the question
$data = '{"DGGroups"[{"DoorGroupID":"1","DoorGroupName":"Default","DoorGroupStatus":"Lock"}{"DoorGroupID":"2","DoorGroupName":"Group 1","DoorGroupStatus":"Unlock"}{"DoorGroupID":"3","DoorGroupName":"Group 2","DoorGroupStatus":"Lock"}{"DoorGroupID":"4","DoorGroupName":"Group 3","DoorGroupStatus":"Unlock"}{"DoorGroupID":"5","DoorGroupName":"Group 4","DoorGroupStatus":"Lock"}]}';
# grab the members of DGGroups
preg_match('/"DGGroups"\[({.*?}+)\]/', $data, $matches);
# split the members into individual elements
$doorgroups = explode("{", $matches[1]);
# get rid of the empty element at the beginning
array_shift($doorgroups);
# now work with each
foreach ($doorgroups as $dg) {
    # decode it, don't forget preg_split stripped off the separator
    $dg = json_decode("{" . $dg);
    # bind the variables to the statement
    $stmt->bind_param("iss", $dg->DoorGroupID, $dg->DoorGroupName, $dg->DoorGroupStatus);
    # execute it
    $stmt->execute();
}

Of course you'll want to do some error checking on the results of mysqli::prepare(), preg_match(), json_decode(), etc.


text:
Q: QlikView: Input Box Not Accepting Values I created a variable vAverageSalary and an input box which serves as a place to change the value of the variable (variable is defined as money). The problem is that nothing happens when I enter numbers in the input box for the variable. Additionaly when I check the value in the 'Variable Overview' for that varable, I see nothing. Even if I try to define here any value for the variable, nothing changes. And the third option I tried was to define any value by going to the 'Properties' of the input box and entering any value in the 'Settings for the Selected Value' (Tab - 'Constraints'). Even when I enter a value here, nothing happes - the system simply ignores everything I enter.
How can I make an input box to take the value I enter in it?
UPDATE: It seems that the problem is when I define the variable inside the input box as 'Money' - I can only set velue when I type for example '121,00 €'. However if I make a text box and try to write out the value of the variable, I get the message "Error: Garbage after expression ','". The input box takes the values in that format, but the output is garbage. And if I type for example any number without '€' sign, than input box ignores my input and gives me the previous value... Why?


text:
Q: Irreducibility of $(ρ,V)$ Let $g$ be a semisimple Lie algebra, and $(ρ,V)$ a finite-dimensional representation of $g.$ We can see that the irreducibility of $(ρ,V)$ implies that $End_{g}(V) = \{kI_n : k \in $C$\}.$ This is due to Schur's lemma, and the semi-simpleness of $g$ is not required. Can you help me to prove the converse part using the semi-simpleness of $g$?
Any help/suggestions would be appreciated. Thanks so much.

A: Hint: If $V = \bigoplus V_i$ with simple representations $V_i$, what is $\mathrm{End}_g(V) = \mathrm{Hom}_g(\bigoplus V_i, \bigoplus V_i$)? Use finite additivity of Hom, and Schur's Lemma.

As an example of why one needs semisimplicity, look at the Lie algebra $g:= \{\pmatrix{a&b\\0&0}: a,b \in \mathbb C\}$ and its natural representation on $V= \mathbb C^2$. Show that $\mathrm{End}_g(V) \simeq \mathbb C$ but $V$ has a proper subrepresentation. Compare with the above to see what exactly semisimplicity is needed for.


text:
Q: Don't quite understand powershells "-Join" and "ConvertTo-Csv" I have this code to create a csv and display it as a table:
$Keys = ("OrderDate","Region","Rep","Product","Units","Unit Cost","Total")
$Csv = @()
$Keys | ForEach-Object {
    $Csv += $_ -Join ","
}
$Csv | ConvertFrom-Csv

My output is:
OrderDate
OrderDate,Region
OrderDate,Region,Rep
OrderDate,Region,Rep,Product
OrderDate,Region,Rep,Product,Units
OrderDate,Region,Rep,Product,Units,Unit Cost
OrderDate,Region,Rep,Product,Units,Unit Cost,Total

OrderDate
---------
Region
Rep
Product
Units
Unit Cost
Total

I would like these lines to be formatted as headers of a table, like this:
OrderDate  Region  Rep  ProductUnits  Unit Cost  Total
-----------  --------  ----  ---------------  -----------  ------

A: What you're attempting can be done like this:
$Keys = "OrderDate","Region","Rep","Product","Units","Unit Cost","Total"
$Object = Select-Object -InputObject 0 -Property $Keys

That's typically most useful when you don't know what the properties are when writing the script. The input object doesn't matter as long as it's a scalar value (i.e., not a collection).
To get the exact output you've specified, you'd have to do $Object | Format-Table because PowerShell defaults to list output for custom objects, but that changes the object into a string so it's just for display.
A more generally useful pattern to create an object when you do know the properties is to do this:
$Object = [PSCustomObject]@{
    "OrderDate" = # Some Value
    "Region" = # Some Value
    "Rep" = # Some Value
    "Product" = # Some Value
    "Units" = # Some Value
    "Unit Cost" = # Some Value
    "Total" = # Some Value
}

Here you instance the object and assign the values you want immediately.


text:
Q: Check if variable is a number smaller than a given number or equal to the text "QUIT" I would to stay in this loop as long as $CHOICE is not "QUIT" or a number smaller than a given integer (variable).
I'm using this : (22 as an example)
NUMBER=22
CHOICE=99
while [ "$CHOICE" -gt "$NUMBER" ] && [ "$CHOICE" != "QUIT" ]; do
  read CHOICE < /dev/tty
done

But if I put let's say "test", the script crashes because it is expecting an integer in the first test.
What can I do to avoid this crash ?

A: The following code will loop while CHOICE is not "QUIT" or an integer less than NUMBER:
NUMBER=22
while :; do
    read CHOICE
    case $CHOICE in
        QUIT) break;;
        *[!0-9]*|'') ;;
        *) test "$CHOICE" -lt "$NUMBER" && break;;
    esac
done

If you also want the loop to exit when the user enters ^D, you should put the read as the loop condition: while read CHOICE; do case $CHOICE ....

A: Tweaks of mosvy's answer:
NUMBER=22
while read CHOICE ; do
  case "${CHOICE}" in
        QUIT)   break ;;
    *[!0-9]*)   ;;
          ?*)   [ "${CHOICE}" -lt $NUMBER ] && break ;;
  esac
done

*

*Don't put read in the loop.

*No need to initialize $CHOICE, and

*changed *) to ?*), making one less conditional -- mosvy's |'' can just fall through.

A: You may need an additional test for alpha characters, like
while [ "$CHOICE" != "QUIT" ] && { [ "${CHOICE//[[:alpha:]]}" != "$CHOICE" ] || [ "$CHOICE" -gt 10 ]; }
  do    read CHOICE < /dev/tty
  done


text:
Q: finding date in sql i need a query to find the date based on year, month, day of the week and weekday number. Say for example, if the question is to find the date of 2nd Sunday of January 2010, the answer should be '2010-01-10'.
Inputs are
Yr   | Mon | Dy  | Dyno
-----------------------
2010 | Jan | Sun | 2
2005 | Jan | Mon | 3
1995 | Feb | Sun | 1
2000 | Feb | Wed | 4
1982 | Mar | Tue | 2
2010 | Mar | Tue | 8

Dyno states dayno

A: The easiest answer to many date-related questions in SQL is to create a calendar table. In your case, if you create a table with the columns you've already shown, and an extra one with the DATETIME value that you want (call it BaseDate), you can get the value you need with a simple query:
select BaseDate
from dbo.Calendar
where Yr = 2010 and Mon = 'Jan' and Dy = 'Sunday' and Dyno = 2

Of course, your calendar table can have 10, 20 or more columns, depending on what values you find useful for your queries.


text:
Q: How to know what is the pangkat of branches i am selected?         Branches

                        <?php

                        $select = "SELECT * FROM branches WHERE access = 'User'";
                        if($result = mysqli_query($conn, $select)){
                        while ($row = mysqli_fetch_array($result)) {
                          $brid = $row['brid'];
                          ?>
                          <input type="checkbox" name="brid[]" value="<?php echo $brid; ?>" onclick="updateArea(this)"><?php echo $brid; ?>
                          <input type="hidden" name="pangkat" value="<?php echo $pangkat; ?>">

                          <?php
                        }
                      }

                        ?>

here is the code i am selecting brid from branches table i already know how to insert multiple rows of selected branches to database i want to know how to insert the pangkat of branches am i selecting.
<?php
require '../db/db.php';

$smsid = $_POST['smsid'];
$brid = $_POST['brid'];
$pangkat = $_POST['pangkat'];
$smssubject = $_POST['smssubject'];
$smscontent = $_POST['smscontent'];
$smsfrom = $_POST['smsfrom'];

for ($i = 0; $i<sizeof($brid); $i++ ){

    $insert = $conn->query("INSERT INTO messages(sms_id,brid,pangkat,subject,message,from_brid,datesent)
                VALUES('$smsid', '".$brid[$i]."','$pangkat',
                '$smssubject','$smscontent','$smsfrom',NOW())");

        echo "";
        echo "";
}?>

here is my action page to insert brid but the pangkat is always blank any help?

A: <?php
require '../db/db.php';

$smsid = $_POST['smsid'];
$brid = $_POST['brid'];
// $pangkat = $_POST['pangkat'];
$smssubject = $_POST['smssubject'];
$smscontent = $_POST['smscontent'];
$smsfrom = $_POST['smsfrom'];

for ($i = 0; $i<sizeof($brid); $i++ ){

    $select = $conn->query(" SELECT * FROM branches WHERE brid = '".$brid[$i]."' ");

    while($rows = mysqli_fetch_array($select)){

        $pangkat = $rows['pangkat'];

    $insert = $conn->query("INSERT INTO messages(sms_id,brid,pangkat,subject,message,from_brid,datesent)
                VALUES('$smsid', '".$brid[$i]."','$pangkat',
                '$smssubject','$smscontent','$smsfrom',NOW())");

        echo "";
        echo "";
    }
}?>

problem solved thanks!


text:
Q: Loading an Visual Studio DLL into Matlab I have a 64-bit DLL compiled from Visual Studio 2010 coded like this example: visual studio Dll and Matlab
When I call loadlibrary in Matlab (64-bit), I get the following error message:
Error using loadlibrary (line 254)
A 'Selected' compiler was not found.  You may need to run mex
-setup.

Any suggestions?

A: As the error message states, you must specify which compiler was used to generate your library. Use mex -setup to do this.
I think Matlab needs to know which compiler was used to generate the library because the ABI is compiler-dependent for C++... Although I see in the other answer that they use extern "C" to export the functions, which should make them compliant with the C ABI, which is more or less standard on x86_64 Windows, so I'm not quite sure about this...


text:
Q: Не правильно работает matcher java Есть HTML-шаблон письма и регулярное выражение, которое работает на regex101.com. С его помощью вместо указанных переменных в формате %name% подставляются необходимые значения. У меня таких переменных несколько в документе.
Проблема в том что Matcher берет первый и последний % и якобы это одно найденное совпадение по регулярному выражению.
Само регулярное выражение выглядит так: %([a-z].+)%. Самое интересное, что на regex101.com всё нормально работает, а в коде нет.
Подскажите решение.

A: Шаблон .+ находит 1 и более символов, отличных от символов перевода строки. Так как + - "жадный" квантификатор, в совпадении сохраняется последовательность знаков от самого левого до самого правого в строке.
Удалите .+ и используйте
%([a-z]+)%

*

*% - символ процента

*([a-z]+) - захватывающая группа (подмаска), находящее 1 и более строчных букв ASCII

*% - символ процента


text:
Q: jquery Datepicker setdate change format I am using jquery UI datepicker on MVC2 to set my startdate picker.
When I go to the 'create' view, I want the datepicker to hold its minimal value- which is today.
But for some reason I see the date format string like this: mm/dd/yyyy HH:MM:SS AM or PM.
only before the user pick a date- after the user picks a date I get the format that I want: mm/dd/yyyy in both of my datepickers- dateStart and dateEnd
and when I go to edit, I get the value from the database (date datatype) and have the same problem.
this is my code:
$(function () {
        var buttonImage = $(".selector").datepicker("option", "buttonImage"); // date image

        // Datepicker
        $('#DateStart').datepicker({
            inline: true,
            showOn: 'both',
            buttonImage: '/Content/calandar2.gif',
            minDate: '+0',
            dateFormat: 'mm/dd/yy',
            onSelect: function (dateStr) {
                var min = $(this).datepicker('getDate') || new Date(); // Selected date or today if none
                $('#DateEnd').datepicker('option', { minDate: min });
            }
        });

        $('#DateEnd').datepicker({
            inline: true,
            showOn: 'both',
            buttonImage: '/Content/calandar2.gif',
            dateFormat: 'mm/dd/yy',
            minDate: '+0'
        });
}

THANK YOU!!!

A: It sounds like your issue is with the HtmlHelper and the DateTime value.
<%=Html.TextBoxFor(model=>model.SomeDate) %>

or
<%=Html.EditorFor(model=>model.SomeDate) %>

Which by default will call DateTime.ToString()
If that is the case you can either convert it to be simply
<%
  var theValue = //something to get your date time and call .ToShortDateString()
%>
<%=Html.TextBox("DateStart", value) %>

If you are using templates you can also do this:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%
    string value;
    if (Model.HasValue && Model.Value != DateTime.MinValue)
        value = Model.Value.ToShortDateString();
    else
        value = string.Empty;
%>
<%=Html.TextBox("", value) %>


text:
Q: Laravel input loop i try to looping my edit form. but the foreach loop doesn't work. anyone can help?

@foreach($siswas as $siswa)
<form id="editform" action="{{route(siswa.update, $siswa->id}}" method="post">
        @method('PATCH')
        @csrf

            Nama
            <input type="text" value="{{$siswa->nama}}" id="nama" name="editNama" class="form-control" >

</form>
@endforeach

A: You should try this:
your edit function like this:
public function edit($id)
    {

        $siswas = Yourmodel::find($id);
        return view('yourviewpath',compact('siswas'));

    }

Your view file like this:
<form id="editform" action="{{route(siswa.update, [$siswas->id]}}" method="post">
        @method('PATCH')

        @csrf

            Nama
            <input type="text" value="{{ old('editNama', $siswas->nama) }}" id="nama" name="editNama" class="form-control" >

</form>

A: Several errors there:

*

*route name should be a string (in quotes),

*route parameter should be an associative array,

*in provided example, closing parenthesis missed

(Assuming that parameter in Route is id), try with
{{ route('siswa.update', ['id' => $siswa->id]) }}

Laravel named routes.

A: You should incorporate siswa in your form id:
@foreach($siswas as $siswa)
<form id="editform-{$siswa->id}" action="{{route(siswa.update, $siswa->id}}" method="post">
        @method('PATCH')
        @csrf

            Nama
            <input type="text" value="{{$siswa->nama}}" id="nama" name="editNama" class="form-control" >

</form>
@endforeach


text:
Q: How to increase the size of JScrollPane pane?
  scrollPane = new JScrollPane(table);
  panel1.add( scrollPane,BorderLayout.CENTER );

Is there a way I can make the scrollPane bigger (wider) ?

A: JScrollPane scrollPane = new JScrollPane(table,
                                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JScrollBar bar = scrollPane.getVerticalScrollBar();
bar.setPreferredSize(new Dimension(40, 0));

This works. I figured it out.

A: When using Border Layout you don't control the size of the somponents in it Consider using GridBag Layout.

A: The JScrollPane is as big as the element it holds. You should make those element(s) wider.
Also, there is the setSize()-method. But you'll most likely want to use the setPreferredSize()-method as mentioned by mre.


text:
Q: fieldset breaks phone numbers on mobile On mobile devices (ios & android), if there is a phone number in a fieldset tag, the phone number is no longer clickable.
<fieldset>

(800) 555-5555 - does not work on mobile

</fieldset>

(800) 555-5555 - works on mobile

Does anyone have a solution? (besides not using fieldset)

A: Usually, Fieldset is used in a form to group elements.
If you only look for a style, use a div with CSS formating.


text:
Q: How to stop disappearing the dropped when I want to disappear the source drag items? I have drag items inside of the Bootstrap button collapse. I click the button and it's show my all drag items. And I can also one item and drop my specific place. But problem is when I click on button for disappear my other items, it's also disappear my drop item too.
HTML:

    <button type='button' class='btn btn-info' data-toggle='collapse' data-target='.draggable'>ClickMe and Drag Item</button>

drag and drop 1

drag and drop 2

Demo code here

A: The problem is even though you changed the relative position of the draggable object, it still belongs to the dropdown hierarchy, so it will respond to the close event of the button
I'm not terribly familiar with jQuery.UI, but there should be some way to clone the object you are dragging. Or if you only want one instance of the draggable element, there is a somewhat trivial way make the element a child of the droppable area using jQuery. --Just remember to work with the elements inside the draggable because you've made the draggable element collapsable when the button is clicked.
Think about the elements you're working with and how they are in relation to the rest of the markup, not the position of where they are on the screen.


text:
Q: Making Submit and Reset have a different border from the input tag border Please how can i make the submit button and reset button have a different border apart from the input tags
     HTML
     <input typ="image" name="submit"     value=" " scr="image.png">

      <input type="image" name="reset"      value=" " scr="reset.png" >

   CSS
   input, textarea, select {
   border: 2px solid red;
   }

I have tried to add another selector with the name submit and reset but both of them still get the values from the input tags border.

A: input[type=image] or give them a class name or give them an id, name is not used for css

A: Write:
id="submit"

In the input tag of the submit button, and then in the CSS, type:
#submit
{
    border: 1px solid black;     /* as an example */
}


text:
Q: Emacs auto-complete for installed library via quicklisp? I'm using Emacs 24.3 + SBCL + Slime + Quicklisp.
Emacs auto-complete works well in slime.
But, I usaully write lisp code in .lisp file where I can't load cl library because .lisp file is not REPL as you know.

How can I do auto-complete without loading lisp file installed via quicklisp?

A: I solved by myself.
Just (ql:quickload :wherever) Then write a lisp code in .lisp file.
Now semantic will work. But, It depends on semantic configuration.
In my case, .el file didn't support auto-complete even if I loaded a library.


text:
Q: Frequently Wifi network disappears on Windows 8 I'm using Windows 8. My Laptop is DELL inspiron 5110 15r. The problem is, I'm getting warning sign on the tray wifi network icon very frequently. When I hover mouse on warning sign, baloon with following message appears "No network access, No internet access".  I have few other devices at home, they work well with this same network. What can be issue?
I'm using win 7 divers for it's wifi card. Maybe it's driver related problem, but I haven't found windows 8 drivers for my laptop.

I can give you teamviewer access if anyone can solve this problem. I can't figure out


text:
Q: Grails data binding: creating instances of an abstract class with a Map hasMany Similar to my last question (Grails databinding: creating instances of an abstract class), I want to use data binding with a class that contains a collection of abstract classes with a hasMany relationship, but in this case, instead of using a List, I'm using a Map.
I created a smalll project with a failing integration test to show the problem that can be found in Github, run it with:
grails test-app -integration -echoOut DataBinding

Anyway, I'll explain the problem by describing the classes and the test here:
class LocalizableContent {
   Map contentByLocale = [:].withDefault { locale -> new Text() }
   static hasMany = [ contentByLocale : Content ]
}
abstract class Content {
   static belongsTo = [ localizableContent : LocalizableContent ]
   static constraints = {
      localizableContent nullable:true
   }
}
class Text extends Content {
   String text
}

As you can see, I'm already using the withDefault trick, but apparently it's not being called by Grails / Spring (I even tried to throw an exception in the default closure to verify that the code is not executed).
For the sake of the test, I also created a LocalizableContentController which is empty. With all that, the following integration test then fails:
    void testMapDatabinding() {
       def rawParams = [ 'contentByLocale[en].text': 'Content' ]
       def controller = new LocalizableContentController()
       controller.request.addParameters(rawParams)
       controller.request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller)
       def localizableContent = new LocalizableContent(controller.params)
       assert localizableContent?.contentByLocale['en']?.text == 'Content'
    }

It says that localizableContent.contentByLocale is a map which looks like ['en': null], so apparently the data binding is understanding the map syntax and trying to create an entry for the 'en' key. But is not trying first to get the entry for that key, since the withDefault is not being called.
The following one tests that the withDefault works fine, and it passes:
   void testMapByDefaultWithNoDatabinding() {
      assert new LocalizableContent().contentByLocale['en']?.getClass() == Text
   }

What am I missing here?

A: withDefault is nothing but a pattern to provide a valid value if you face an unknown key. For example, consider the below use case:
def map = [:].withDefault{k->
    println k //Should print 'a'
    10
}

map.test = 32

assert map.test == 32
assert map.a == 10

It takes the unknown key as the parameter, you cannot pass in any value to it, which is kind of logical, because it provides a default value instead of a value being provided.
In your case, the data binding would work if set the value to Text like:
Map contentByLocale = [:].withDefault { locale ->
    //locale is the key. 'en' in this case
    new Text(locale: locale, text: 'Content')
}

provided you have your Text class defined as
class Text extends Content{
    String locale
    String text
}


text:
Q: How to convert an image from device to a 3D Tensor in tfjs-react-native? There's an example in the documentation https://js.tensorflow.org/api_react_native/0.2.3/#decodeJpeg but it suits only for a situation when you fetch by URL. What to do if I have URI of an image stored on the device?

A: The solution is given in this issue
I report it here for the sake of clarity:

Digging into this it looks like fetch is not a good fit for loading these types of files. The api our custom fetch is trying to implement leaves behavior for file:// scheme urls undefined. I probably wouldn't rely on on it for this even where it seems to work. Instead I would use an existing file reading mechanism in react native to get the data. You want to be able to read the file data into one of two formats:

A UInt8Array
A base64 encoded string (which will then be converted to a UInt8Array)
Here is a skeleton of some code using expo-filesystem that you can adapt to your code. We do something similar in our bundleResourceIO model loader (though we use a different library for reading the file).

import * as FileSystem from 'expo-file-system';

const fileUri = 'NON-HTTP-URI-GOES-HERE';
const imgB64 = await FileSystem.readAsStringAsync(fileUri, {
    encoding: FileSystem.EncodingType.Base64,
});
const imgBuffer = tf.util.encodeString(imgB64, 'base64').buffer;
const raw = new Uint8Array(imgBuffer)
const imageTensor = decodeJpeg(raw);


text:
Q: Is there a proved performance and memory usage benchmark on the SWT & Swing? I want to know about SWT & Swing , memory usage and performance. which one has better performance and which one consumes less memory.
Is there a proved benchmark on these measures or everybody with good experience in these fields.
thanks


text:
Q: Print SQL Queries from Access in C# I'm writing a program in C# that interacts with an Access Database. In this database, there are queries already set up. Is it possible to print the tables those queries create in Access from my program (in other words, an Access print dialog comes up with the query-created table)? If so, how would I go about doing that?
Thank you.
Note: the database file is a .mdb file.

A: I believe what you are describing is Access Automation.
MSDN has a number of helpful articles on the subject, including
How to automate Microsoft Access by using Visual C#
Specifically, check the section titled Print or Preview an Access Report


text:
Q: Visual Studio 2010: Building toolwindow on the fly in PowerShell I would like to build a Visual Studio toolwindow "on the fly" from PowerShell code executed in a PowerShell host running inside Visual Studio, with access to $DTE. Any ideas if this is possible in PowerShell, and if so: how?

A: As far as I can tell, in order to call $DTE.Window.CreateToolWindow2 you need a UserControl class in an assembly (see MSDN). That's going to make it very hard to do usefully from PowerShell -- I mean, you can compile C#/VB code using Add-Type, but there's not much point in involving PowerShell.
You can create WPF UI's using PowerBoots as Oisin suggested, but the new ToolWindow stuff really seems to require an assembly.

A: Take a look at http://powerboots.codeplex.com for building WPF-based UI in powershell.
-Oisin


text:
Q: Visual Studio 2015 Cordova Windows 10 > Blank/white screen after associated with the existing windows store app Without associating the app with the store, i can run and debug the cordova app on my devices (all works fine). But after associating the app with the store (or after built a package for the store), the app starts and i get a white screen, no errors in visual studio!
I have installed the update 3 and tried to run in release mode, but no success.
No errors occur.
I Use:
- Visual Studio 2015 with Update 3
- Node Version 4.5.0
- Cordova Version 6.3.1
- and release the app for windows 10
========================
I found out that the package name was changed after assocating with store.
So i changed the package name at the start page option to the new one in the appxmanifest.
After that the app starts and i see my page, but with many errors, i cant interact now.
Here the errors:

*

*JavaScript runtime error: 'Windows' is undefined cordova.js (1559,13)

*deviceready has not fired after 5 seconds.

*Channel not fired: onPluginsReady

*Channel not fired: onCordovaReady

from the debugger:

*

*"WWAHost.exe" (Skript): "Skriptcode (MSAppHost/3.0)" geladen.

*Es wurde eine Ausnahme ausgelöst: in Zeile 596, Spalte 9 in ms-appx-web://........./www/WinJS/js/base.js
0x800a138f - JavaScript runtime error: Unable to get property 'UI' of undefined or null reference

*Ausnahmefehler in Zeile 1559, Spalte 13 in ms-appx-web://......../www/cordova.js
0x800a1391 - JavaScript runtime error: 'Windows' is undefined

Who can help me?
Kevin

A: I ran into the same issue.
In fact, when we associate app with the store, association change "Package Name" with name generated to the store.
The result is : start page don't know where is "index.html" because package name changed.
To resolve it, cordova team added two preferences :
<preference name="WindowsStoreIdentityName" value="12225TOTO42.3355241V9C2T6" />
<preference name="WindowsStorePublisherName" value="CN=9985D2C8-IUI5-4272-TOTO-EBR6FE26877A" />

You just have to add it to your config.xml and fill fields with your app identity informations (retrieve this values from App Management --> App Identity in the Dev Center)
Association should be successful now !
The issue reference is here : https://github.com/phonegap/build/issues/506

A: I had the same problem but I resolve it now.
When you associate the application to store, Visual Studio changes these values:

but it does not change the value of package name in the application tab:

so the index.html is not found and the app shows a blank screen.
To resolve it, you must add two preferences in config.xml file as described here:
https://stackoverflow.com/a/40658027/2496666
and rebuild the project from CLI with the usual command:
cordova build windows

after rebuild the project, the values shown in the following image must be the same:

A: i found a solution!
The error only occur, when i install cordova and plugins over CLI, but when
i start a cordova project over visual studio 2015 and use the integrated plugin manager -> so it works without any error.
Kevin

A: before associate app in visual studio
ionic plarform add windows
cordova build -- --packageCertificateKeyFile="CordovaApp.Windows10_StoreKey.pfx" --packageThumbprint="8d66824...."
and you have associated app without visual studio


text:
Q: issues using the Multer file upload package & express.js So I faced a couple of issues using Multer.
1- The official DOCS advises against using Multer as a global middleware that's run on every single request, and that it should be passed to each route individually as per need as a security measure.
Multer functions just fine when I use it globally on the main app.js file, which is a bad practice, but when I use it as instructed, it returns an invalid CSRF token error (note that I'm passing the csrfToken as a hidden input that's parsed during form submission).
2- The second problem stems from the fact that form validation doesn't interrupt file uploading.
So whenever a form is submitted, even if the validator deems some of the fields invalid and acts accordingly by flashing some error and asking the user to enter a valid input, Multer would still upload the file nevertheless. I want to make it so that if any validation error comes up, even if the uploaded file itself is valid, Multer doesn't upload the file.


text:
Q: Update To MvvmCross 5.2 Throws Navigation Service Compiler Error On Navigate Method I updated MVVMCross from v5.x to v5.2 and had to update my viewmodel navigation service code to change the Initialize method required by the navigation service for parameter passing to the new Prepare method. However, now I am faced with the following compilation error on the Navigate method of the IMvxNavigationService when trying to navigate using a parameter object:

Error CS1501: No overload for method 'Navigate' takes 1 arguments

As far as the documentation goes, I thought my code was correct but am I missing something? My code is as follows...
ViewModelA:
public class ViewModelA : MvxViewModel
{
   ...

   public void DoNavigate()
   {
      var navigationService = Mvx.Resolve<IMvxNavigationService>();
      navigationService.Navigate<ViewModelB, PageNavParameters>(
         new PageNavParameters
         {
            PageDisplayType = MyPageDisplayTypeEnum.PageDisplayType1,
            ObjectID = "someIDstring"
         }
      );
   }

}
ViewModelB (inherits from a super class viewmodel):
public class ViewModelB : SuperViewModel
{...}

SuperViewModel (inherits from a base viewmodel (which in turn inherits from MvxViewModel), and because it already has a base, SuperViewModel implements the IMvxViewModel interface):
public class SuperViewModel : BaseViewModel, IMvxViewModel<PageNavParameters>
{

    public void Prepare(PageNavParameters pageNavParameters)
    {
        CurrentPageParameters = pageNavParameters;
    }

    public PageNavParameters CurrentPageParameters { get; set; }

    ...
}

My navigation service code was functioning properly before the update and change to the Prepare method, however I'm a bit stumped here. It seems as if the Navigate method is looking for ViewModelB to be passed as a parameter, however a type can't be passed here, and I am already strongly typing the method itself with ViewModelB in the call. Apologies in advance if it's something minor I missed, and any help is much appreciated.


text:
Q: Pattern-search for xml-comments I´m using ReSharper 2019 and I am trying to search and replace some common code-smells in our solution. The one here is the following:
/// <summary>
/// OnCreate
/// </summary>
/// <param name="hook"></param>
public void OnCreate(object hook)
{
    ...
}

which is pure noise. Thus I created a custom search&replace-pattern in ReSharper:

Search-pattern:
/// <summary>
/// $name$
/// </summary>
/// $comments$
public $type$ $name$($args$)
{
    $statements$
}

Replace pattern:
/// <inheritdoc />
public $type$ $name$($args$)
{
    $statements$;
}

This should create the following:
/// <inheritdoc />
public void OnCreate(object hook)
{
    ...
}

but I get this instead:
/// <summary>
/// OnCreate
/// </summary>
/// <param name="hook"></param>
/// <inheritdoc />
public void OnCreate (object hook
    {
    })
    {
        ...
    }

Has anyone an idea if and how I can replace within xml-comments?


text:
Q: If a value then return all column so I have a similar table like this:

Employee ID
Name
Function
Level

2324
Bruno
Unpaid Student
D

4378
John
Operator
B

1218
Barack
Operator
B

What I want to is to apply a formula where: if the person is an "Operator" or "Unpaid Student" then return me the whole line and all inputs. Because I am going to create one sheet for each function. So, my desired output will be:
(Unpaid Student Sheet)

Employee ID
Name
Function
Level

2324
Bruno
Unpaid Student
D

(Operator Sheet)

Employee ID
Name
Function
Level

4378
John
Operator
B

1218
Barack
Operator
B

Thanks a lot!!

A: I would apply the formula in the main sheet and use Pivot Table in different sheets to filter. This way I don't have to worry about broken formulas in 2 different sheets.


text:
Q: Elasticsearch:how to choose java client? I'm trying to use ELK in my new module.After reading 'get start' doc,I'm trying to write java code to perform index,get,delete operation.
Official doc introduces 'TransportClient'.However,the doc says that 'TransportClient' may be deprecated in further version.It's advised to use 'Java High Level Rest Client'.Furthermore,there is 'Java Low Level Rest Client'.
In conclusion , there are 3 types of clients:

*

*Java High Level Rest Client

*Java Low Level Rest Client

*TransportClient

By the way,there is another way to use ES API.Use spring boot RestTemplate.I think it's complex because maybe I have to write query json.
I'm so confused that I dont know which one I should use.
My ES version is :5.6.3

A: I recommend you to use Jest Client which is simple, basic, and easy to install. I'm using this one, and it works perfect.


text:
Q: Solution to the Heat Equation: Time-dependent Source, Spherical Coordinates, Insulating Boundary Condition I am looking to solve the PDE that takes the form of $$\frac{\partial C}{\partial t}-Q(t)=D\nabla^2C$$
where $$\nabla^2C = \frac{1}{r^2}\frac{\partial}{\partial r}r^2\frac{\partial C}{\partial r}$$
I have read that eigenfunction expansion is an option for homogeneous boundary conditions. My boundary conditions are the following:
$$C(r=0,t) = A(t)$$ and
$$\frac{\partial C}{\partial r}\Bigr|_{r=\bar{R}}=0$$
where $\bar{R}$ represents the distance from the source where the insulating "wall" exists.
My initial condition is:
$$C(r>0, t=0) = C_b = 0$$
Do any solutions exist for this problem statement?


text:
Q: Explanation on WordPress' rewrite rules I found these rewrite rules in the .htaccess of my WordPress site:
RewriteEngine On
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

I know that this basically refers everything to index.php. But how does it work? What rule does what?

A: I found some reference here: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
RewriteEngine On enables the rewrite module.
RewriteRule ^index\.php$ - [L] makes sure that if index.php is called, no other rules are executed. The - is to make sure no rewrite will occur, and the [L] flag indicates that no other rules should be executed.
RewriteCond %{REQUEST_FILENAME} !-f adds a condition to the following rewrite rule. This condition says that the requested filename is not (!) an existing file.
RewriteCond %{REQUEST_FILENAME} !-d is the same, but for an existing directory.
RewriteRule . /index.php [L] says that everything (.) should be rewritten to /index.php, and that this is the last rule to execute ([L]).


text:
Q: I cant enter characters in password field. I can enter number only I used the following code to encrypt the password using md5 and store it in the database.
public partial class register : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection("Data Source=Shihab-PC;Initial Catalog=test;User ID=sh;Password=admin1");
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter ad = new SqlDataAdapter();
        DataSet ds = new DataSet();
        SqlDataReader dr;
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection myconnection;
            SqlCommand mycommand;
            string query;
            myconnection = new SqlConnection("Data Source=Shihab-PC;Initial Catalog=test;User ID=sh;Password=admin1");
            if (!Page.IsPostBack)
            {
                myconnection.Open();
                query = "select * from Users";
                mycommand = new SqlCommand(query, myconnection);
                dr = mycommand.ExecuteReader();
                dr.Read();
                int count = Convert.ToInt16(dr[0].ToString());
                while (dr.Read())
                { count++; }
                TextBox4.Text = Convert.ToString(count + 1);

            }

        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection myconnection;
            SqlCommand mycommand;
            int ra;
            string query;
            myconnection = new SqlConnection("Data Source=Shihab-PC;Initial Catalog=test;User ID=sh;Password=admin1");
            myconnection.Open();

            MD5CryptoServiceProvider md5hasher = new MD5CryptoServiceProvider();
            Byte[] hashedDataBytes;
            UTF8Encoding encoder = new UTF8Encoding();
            hashedDataBytes = md5hasher.ComputeHash(encoder.GetBytes(TextBox2.Text));

            StringBuilder hex = new StringBuilder(hashedDataBytes.Length * 2);
            foreach (Byte b in hashedDataBytes)
            {
                string x = b.ToString() + " ";
                hex.AppendFormat("{0:x2}", b);

            }

            query = "Insert into Users values(" + TextBox4.Text + ",'" +
                                                   TextBox3.Text + "','" +

                                                   hex.ToString() + "','" +

                                                   TextBox1.Text + "','" +
                                                    TextBox5.Text + "','" +
                                                    TextBox6.Text + "','" +
                                                    TextBox7.Text + "','" +
                                                    TextBox8.Text + "','" +
                                                    TextBox9.Text + "','" +
                                                   TextBox10.Text + "')";

            mycommand = new SqlCommand(query, myconnection);
            ra = mycommand.ExecuteNonQuery();
            if (ra > 0)
            {
                string msg = "alert('Record Inserted Sucessfuly')";
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", msg, true);
                Response.Redirect("signin.aspx");
            }
            else
            {
                string msg = "alert('Unable to Insert Record ')";
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", msg, true);
            }
            myconnection.Close();
        }
    }

the problem when I run the code and enter characters in password field I get the following
 error (Conversion failed when converting the varchar value '1234567yY' to data type int.)

A: First Option:  Specify the columns in your INSERT SQL.
INSERT INTO Users (UserID, Col2, Col3 ...) VALUES (...)

Second Option: See what query actually is and debug it with SQL Server Management Studio.
Put a breakpoint on this line and check the Locals for query.
mycommand = new SqlCommand(query, myconnection);

Third Option: Use a parameterized query and set the values in the Parameters property of the command.
Those maintaining this after you will thank you and you'll get rid of the SQL injection possibility in this section of code.

A: Your code has a lot of issues.
It's going to leak connections, it's ripe for SQL Injection, and it's very brittle.  Taking these one at a time.
First, you should wrap every object that implements IDisposable in a using clause.  This is the best practice way of making sure the objects get cleaned up at the appropriate time.  See this question for an example: c# closing sqlconnection and sqldatareader or not?
On a very lightly used system you may not notice the issue do to connection pool recycling.  However, as soon as you get any level of traffic this code will blow up in interesting and sometimes unpredictable ways.
Second, to help protect against sql injection do NOT use string concatenation to build your queries.  Instead use parameters.  @decyclone's answer shows an example of how to do this.  It would be trivial to crack the code you have now.
Third, your queries are very brittle.  Your insert statement depends on the order of the fields in the users table and, therefore, that the table is never modified.  The first time you either reorder those fields OR add a new one your code will break.  And you won't find this bug until runtime.  You should explicitly set which fields you are inserting into.  For example:
insert into Users(Username,Password) values('SomeUser', 'SomePassword')

A: Looks like you are trying to insert a varchar value into an int type column in database.
A better way to go would be using Command Parameters instead to prevent errors like this.
Example:
SqlCommand command = new SqlCommand("Insert into Users(UserName, Password) Values(@UserName, @Password)", connection);
command.Parameters.AddWithValue("@UserName", "SomeUser"); // You pass something else instead of "SomeUser"
command.Parameters.AddWithValue("@Password", "Password"); // You pass something else instead of "Password"
command.ExecuteNonQuery();


text:
Q: Converting Packer 1.6 vsphere-iso configuration code from JSON to HCL2 With the release of Packer 1.6 came several depreciated fields in the vsphere-iso builder. From the looks of it, seems to be a format/type change because the fields actually still exists but just as properties it seems. An example of the changes are the following:

Working in Packer 1.5.6:
JSON
"disk_size": 123456,
"disk_thin_provisioned": true
"network": "VM Network",
"network_card": "vmxnet3"

Working in Packer 1.6.0:
JSON
"storage": [
    {
        "disk_size": 123456,
        "disk_thin_provisioned": true
    }
],
"network_adapters": [
    {
        "network": "VM Network",
        "network_card": "vmxnet3"
    }
]

The issue I have at the moment is I'm using Packer 1.6.0 and am trying to convert the above working JSON code to HCL2. I can't figure out the HCL2 syntax that supports the changes that were made in Packer 1.6.0.
I've tried the following:
network_adapters = {
    network_card = "vmxnet3"
    network = "VM Network"
}

Output:

An argument named "network_adapter" is not expected here.

network_adapters = (
    network_card = "vmxnet3"
    network = "VM Network"
)

Output:

Error: Unbalanced parentheses
on .\Packer\ConfigFileName.pkr.hcl line 19, in source "vsphere-iso"
"Test":   18:     storage = (   19:       disk_thin_provisioned = true
Expected a closing parenthesis to terminate the expression.

network_adapters = [
    network_card = "vmxnet3",
    network = "VM Network"
]

Output:

Error: Missing item separator
on .\Packer\ConfigFileName.pkr.hcl line 19, in source "vsphere-iso"
"Test":   18:     storage = [   19:       disk_thin_provisioned =
true,
Expected a comma to mark the beginning of the next item.

I've also tried several other permutations of different collection syntax together with no luck so far. Any suggestions or tips would greatly be appreciated

A: The correct syntax is the following:
network_adapters  {
    network_card = "vmxnet3",
    network = "VM Network"
}

Note that it's not using an assignment operator = between network_adapters and {
Credit goes to SwampDragons over on the Packer forums for pointing this out.

If you're interested in knowing why: There was a change to how maps are treated in HCL2 back in May 2020 with the release of Packer 1.5.6

core/hcl2: Maps are now treated as settable arguments as opposed to blocks. For example tags = {} instead of tags {} [GH-9035]

Reference: https://github.com/hashicorp/packer/blob/master/CHANGELOG.md#156-may-1-2020


text:
Q: Running Octave tasks from Python I have a pretty complex computation code written in Octave and a python script which receives user input, and needs to run the Octave code based on the user inputs. As I see it, I have these options:

*

*Port the Octave code to python.

*Use external libraries (i.e. oct2py) which enable you to run the Octave/Matlab engine from python.

*Communicate between a python process and an octave process. One such possibility would be to use subprocess from the python code and wait for the answer.

Since I'm pretty reluctant to port my code to python and I don't want to rely on maintenance of external libraries such as oct2py, I am in favor of option 3. However, since the system should scale well,  I do not want to spawn a new octave process for every request, and a tasks queue system seems more reasonable. Is there any (recommended) tasks queue system to enqueue tasks in python and have an octave worker on the other end process it?

A: The way it is described here, option 3 degenerates to option 2 because Octave does not have an obvious way (an API or package) for the 'Octave worker' to connect to a task queue.
The only way Octave does "networking" is by the sockets package and this means implementing the protocol for communicating with the task queue from scratch (in Octave).
The original motivation for having an 'Octave worker' is to have the main process of Octave launch once and then "direct it" to execute functions and return results, rather than launching the main process of Octave for every call to a function.
Since Octave cannot do 'a worker' (that launches, listens to a 'channel' and executes code) out of the box, the only other way to achieve this is to have the task queue framework all work in Python and only call Octave when you need its functionality, most likely via oct2py (i.e. option 2).
There are many different ways to do this ranging from Redis, to PyPubSub, Celery and RabbitMQ. All of them straightforward and very well documented. PyPubSub does not require any additional components.
(Just as a note: The solution of having an 'executable' octave script, calling it via Python and blocking until it returns is not as bad as it sounds however and for some parallel-processing frameworks it is the only way to have multiple copies of the same Octave script operate on different data segments.)

A: All three options are reasonable depending on your particular case.

I don't want to rely on maintenance of external libraries such as oct2py,  I am in favor of option 3

oct2py is implemented using option 3. You can reinvent what it already does or use it directly. oct2py is pure Python and it has permissive license: if its development were to stop tomorrow; you could include its code alongside yours.


text:
Q: Android audio recorder api I am using the android audio recorder api. How do I get the duration of clip that was recorded.
Is there any built in method? I only see setmaxtime(); ?

A: setmaxtime() is not actually method.
setMaxDuration() it actually set that how much time it will be recorded. if you set
setMaxDuration(-1), it will be recorded untill you stop or till your sdcard not finished.
if you set setMaxDuration(10 * 1000) (that is milisec) that means it will automatically stopped after 10 sec.

A: Just put this method in your Utils class as static and pass file path of recorded file.
Note: Here you will get duration in milliseconds.
Android gives class named as MediaMetadataRetriever to fetch all the details of any file type like size,width,height,duration,codec format,etc.
`
public static long getAudioDurationByFilePath(String aFilePath){
        long mMilliSeconds=0;
        try{
            MediaMetadataRetriever lMediaMetaDataRetriever = new MediaMetadataRetriever();
            lMediaMetaDataRetriever.setDataSource(aFilePath);
            String lDurationString = lMediaMetaDataRetriever.extractMetadata(
                    MediaMetadataRetriever.METADATA_KEY_DURATION);
            mMilliSeconds =  Long.parseLong(lDurationString);
        }catch(Exception e){
            Log.w("AudioUtils","SetDataSource ON NULL OBJECT REFERENCE");
            e.printStackTrace();
        }
        Log.w("AudioUtils","returning duration: "+mMilliSeconds);
        return mMilliSeconds;
    }

`


text:
Q: will the jquery.jplayer render the videos from akamai Currently Im using jquery.jplayer with which Im able to play the videos which are in my local machine.Will this js be able to render the videos from akamai server or do we need any script change for that.I will not be able to test that locally with the akamai server, so just want to check on that.
Thanks,
Balaji.


text:
Q: Datastax error: Mismatch between Solr key field id with type text and Cassandra key alias key with type text I use DataStax Enterprise 3.2. When running the example on http://www.datastax.com/docs/datastax_enterprise3.0/solutions/dse_search_load_data
There is an error in step 2, insert value key shall be string like, '123'.
Everything works fine until step 8. When I run,
curl "http://localhost:8983/solr/admin/cores?action=CREATE&name=mykeyspace.mysolr"

I got errors,
<lst name="responseHeader"><int name="status">500</int><int name="QTime">229</int></lst><lst name="error"><str name="msg">Unable to create core: mykeyspace.mysolr</str><str name="trace">org.apache.solr.common.SolrException: Unable to create core: mykeyspace.mysolr
....
....
Caused by: java.lang.IllegalStateException: Mismatch between Solr key field id with type text{class=org.apache.solr.schema.TextField,analyzer=org.apache.solr.analysis.TokenizerChain,args={class=solr.TextField}} and Cassandra key alias key with type text
    at com.datastax.bdp.search.solr.core.Cql3CassandraSolrSchemaUpdater.validateUniqueKeyStructure(Cql3CassandraSolrSchemaUpdater.java:226)
    at com.datastax.bdp.search.solr.core.Cql3CassandraSolrSchemaUpdater.update(Cql3CassandraSolrSchemaUpdater.java:39)
    at com.datastax.bdp.search.solr.core.CassandraCoreContainer.create(CassandraCoreContainer.java:282)
    ... 29 more

Am I missing some configuration? Thanks.

A: The Solr "text" (solr.TextField) type is really tokenized text which has no single, unique value for a sequence of tokens, while the Cassandra "text" type corresponds to the single-valued Solr "string" (solr.StrField) type.
This exception is alerting you to the likelihood that you should be using the Solr "string" type to match the Cassandra "text" type.
I just checked the doc link you gave and I do in fact see that the "id" field has type "string". Did you manually enter the incorrect type, as "text" rather than "string"?


text:
Q: Why is my code coverage 0% in the Sandbox To stop automatic transfer of open activity Ownership related to account/case I have created a trigger on task and cases which calls an apex class.
Apex class:
Task
Public class taskTrigger{
    public static void Task(){
        for(Task t: (List<Task>) Trigger.new){
             t.Custom_ownerText_field__c = t.OwnerId;
        }
    }
}

Case
public class caseClass{
public static void syncTaskOwner( Map<Id, SObject> oldParents, Map<Id, SObject> newParents ){
        Set<Id> changedOwnerIds = new Set<Id>();
        // Identify all Parents that have a changed Owner
        for( SObject parent : newParents.values() ){
            SObject oldParent = oldParents.get((Id)parent.get('Id'));

            if( parent.get('OwnerId') <> oldParent.get('OwnerId') ){
                changedOwnerIds.add((Id)parent.get('Id'));
            }
        }

        // Find all the tasks (repeat for Events if required) that are not closed for the parent records that had new Owners
        List<Task> restoreTaskOwner = new List<Task>();

        // revert the owner on the found tasks
        for(Task tsk : [SELECT Id, OwnerId, Custom_ownerText_field__c  FROM Task Where WhatId IN :changedOwnerIds AND IsClosed = FALSE AND Last_Assigned_User__c <> null]){
            System.debug('tsk.OwnerId..' + tsk.OwnerId);
            System.debug('tsk.Custom_ownerText_field__c ..' + tsk.Last_Assigned_User__c);
            if (tsk.OwnerId <> tsk.Custom_ownerText_field__c ) {
                tsk.OwnerId = tsk.Custom_ownerText_field__c ;
                restoreTaskOwner.add(tsk);
            }
        }
        if(!restoreTaskOwner.isEmpty())
        update restoreTaskOwner;
    }}

Apex Trigger:
Task
trigger taskTrigger on Task (before insert, before Update) {
if(trigger.isInsert || trigger.isUpdate){
taskTrigger.Task();
}}

Case
Trigger CaseTrigger on Case (before insert,before update){
if(Trigger.isAfter){ if(Trigger.isInsert || Trigger.isUpdate){
caseClass.syncTaskOwner(trigger.newMap, trigger.oldMap);
} }

I have created 2 different test classes both has 0% code coverage.
Test Class
Test Class 1:
@isTest
public class TestClass1{
@isTest
static void TestM1(){
    Account acc = new Account(Name = 'Test Acc');
    Insert acc;
    Case ca = new Case(Name__c= 'Test', origin = 'web', Status = 'New');
    Insert ca;
    Task ta = new Task();
    ta.Type = 'Email';
    ta.Status = 'New';
    ta.Description = 'Test SA';
    ta.OwnerId = userinfo.getUserId();
    ta.WhatId = ca.Id;
    ta.Custom_ownerText_field__c = userinfo.getUserId();
    Insert ta;
    Profile p = [SELECT Id FROM profile WHERE Name = 'System Administrator'];
    User u = new User(ProfileId = p.Id , Alias = 'Test', Username = 'Test', Email='Test@Test.com', EmailEncodingKey = 'UTF-8', LastName= 'Test',
                      LanguageLocaleKey = 'en_US', LocaleSidKey = 'en_US', TimeZoneSidKey='America/Los_Angeles');
    ta.ownerId = u.Id;
    update ta;
    ca.ownerId = u.Id;
    update ca;
}
}

Test Class 2:
@isTest
public class TestClass2{
@TestSetup
static void setup(){
    Account newAcct = new Account(
        Name = 'Test'
    );
    insert newAcct;

    Case newCase = new Case(
        Subject = 'test'
        , Status = 'new'
    );
    insert newCase;

    Task newTsk = new Task(
        //WhatId = newAcct.Id
        WhatId = newCase.Id
        , Subject = 'Test'
    );
    insert newTsk;
}

@IsTest
static void syncTaskOwnerTest(){
    Task[] existingTasks = [
        SELECT Id, OwnerId, Custom_ownerText_field__c , WhatId
        FROM Task
        Where IsClosed = FALSE AND Custom_ownerText_field__c <> null
    ];
    System.assert( existingTasks.size() == 1, existingTasks );
    System.assertEquals( existingTasks[0].Custom_ownerText_field__c , UserInfo.getUserId() );
    System.assertEquals( existingTasks[0].Custom_ownerText_field__c , existingTasks[0].OwnerId );

    User[] usr = [SELECT Id FROM User WHERE IsActive = true AND Id != :UserInfo.getUserId() LIMIT 1];

    Test.startTest();
    update new Case(
        Id = existingTasks[0].WhatId
        , OwnerId = usr[0].Id
    );
    Test.stopTest();

    existingTasks = [
        SELECT Id, OwnerId, Custom_ownerText_field__c , WhatId
        FROM Task
    ];
    Account acct = [SELECT Id, OwnerId FROM Account LIMIT 1];
    system.assertEquals( usr[0].Id, acct.OwnerId );
    System.assert( existingTasks.size() == 1, existingTasks );
    System.assertEquals( existingTasks[0].Custom_ownerText_field__c , UserInfo.getUserId() );
    System.assertEquals( existingTasks[0].Custom_ownerText_field__c , existingTasks[0].OwnerId );
}
}

Plese let me know if you have any questions.
Thank you in advance!

A: Your unit test attempts to execute the functionality under consideration by performing DML inserts and updates. However, your post does not contain - and your code coverage suggests you either do not have, or have failed to deploy - an Apex trigger.
The classes TaskTrigger and CaseClass will not be called unless an active Apex trigger is present on the relevant object and calls the class. If you do have an Apex trigger, ensure that it is active and that the DML event you desire does in fact call the class.


text:
Q: How can I find the length of the third side of any triangle? I will know the length of two sides of any triangle that I use, but I will not know any of the angles (unless there is a fast way to figure this out in the field). The following is a link to an example of what I could be dealing with (not to scale and not an image because I'm new.....). http://imgur.com/aYGR2lM
Don't down vote my question because I don't completely know what I'm doing. That is why I asked in the first place. How could I find the angle where I am at in the field?

A: If you don't know the angle, you can't know the length of the third side.
Think about it, there's tons of triangle with two sides with the same length. You'll need more information - angle, area, something...


text:
Q: Passing value with InsertData to the DE in Cloud Pages with AmpScript doesn't work I'm trying to create a technical and completely empty landing page in Cloud Pages that's going to be used for passing values to a Data Extension and then redirecting the person to website. I'm new to AmpScript but to achieve this result I prepared the followin:

*

*Link redirecting to the Cloud Pages LP in the email

<a href="%%=redirectto(CloudPagesURL(123))=%%"

*

*Code in the above-mentioned Cloud Pages LP that is supposed to insert data to the ButtonClicked column of DE (Test_DE) and after that redirect the person to the website.

%%[

var @buttonClicked
set @buttonClicked = "true"

set @insert = insertData("Test_DE","ButtonClicked", @buttonClicked)

%%=Redirect('https://google.com/')=%%

]%%

This code doesn't work and I'm pretty sure that the problem is with the insertData function as the Redirect worked fine when tested alone. Could you please point me in the right direction? What I'm doing wrong?

A: Your InsertData is correct. However, you are mixing Ampscript block with inline Ampscript in your redirect function. You should use this instead:
%%[

var @buttonClicked
set @buttonClicked = "true"

set @insert = insertData("Test_DE","ButtonClicked", @buttonClicked)

If (@insert > 0) then
Redirect('https://google.com/')
Else
Outputline("Something went wrong")
Endif

]%%