text:
Q: Need to run a c# dll from the command line I have a c# dll defined like this:
namespace SMSNotificationDll
{
    public class smsSender
    {
        public void SendMessage(String number, String message)
        {
            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = "c:\\Program Files\\Java\\jdk1.6.0_24\\bin\\java";
            info.WorkingDirectory = "c:\\";
            info.Arguments = "-jar SendSms.jar "+number + " "+message;
            info.UseShellExecute = false;
            Process.Start(info);
        }
    }
}

and i need to execute it from the commandline.
Is there any way I can run it through rundll32?
When I run it with this :
rundll32 SMSNotificationDll.dll, SendMessage 0749965244 hello

I get missing entry: SendMessage.

A: RunDll32 only works with DLLs specifically designed to be called from it. See http://support.microsoft.com/kb/164787 for more information.
The easiest way to run the code in that DLL from the command line would be to make a simple C# command line app whose sole purpose is to call that method.

A: There is a trick to create unmanaged exports from c# too - https://www.nuget.org/packages/UnmanagedExports
How does it work?
Create a new classlibrary or proceed with an existing one. Then add the UnmanagedExports Nuget package. This is pretty much all setup that is required.
Now you can write any kind of static method, decorate it with [DllExport] and use it from native code. It works just like DllImport, so you can customize the marshalling of parameters/result with MarshalAsAttribute.
During compilation, the task will modify the IL to add the required exports.
class Test
{
  [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
  public static int TestExport(int left, int right)
  {
     return left + right;
  }
}

A: Why don't you just create a simple console application which refers to the DLL as a class library?
namespace SMSNotificationDll
{
    public class SmsSenderProgram
    {
        public static void Main(string[] args)
        {
            // TODO: Argument validation
            new smsSender().SendMessage(args[0], args[1]);
        }
    }
}

Btw, I'd rename smsSender to something like SmsSender.

A: See this question you can't run a .NET dll using rundll32


text:
Q: Spring Boot WSDL SOAP web service application does not start I am trying to start a WSDL-SOAP web service application but it doesn't start. Gives the below exception:
2020-11-30 22:28:12.521  INFO 97564 --- [           main] c.c.ws.soap.SpringBootApplicationRun     : Starting SpringBootApplicationRun on Ramazans-MacBook-Pro.local with PID 97564 (started by rdemir in /Users/rdemir/Projects/METU/SM704/Project Phase 2)
2020-11-30 22:28:12.525  INFO 97564 --- [           main] c.c.ws.soap.SpringBootApplicationRun     : No active profile set, falling back to default profiles: default
2020-11-30 22:28:13.304  INFO 97564 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.ws.config.annotation.DelegatingWsConfiguration' of type [org.springframework.ws.config.annotation.DelegatingWsConfiguration$$EnhancerBySpringCGLIB$$6d2d075b] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-11-30 22:28:13.330  INFO 97564 --- [           main] .w.s.a.s.AnnotationActionEndpointMapping : Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
2020-11-30 22:28:13.597  INFO 97564 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-11-30 22:28:13.623  INFO 97564 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-11-30 22:28:13.623  INFO 97564 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/9.0.13
2020-11-30 22:28:13.639  INFO 97564 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/rdemir/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2020-11-30 22:28:13.757  INFO 97564 --- [           main] o.a.c.c.C.[.[localhost].[/wsdlfirstws]   : Initializing Spring embedded WebApplicationContext
2020-11-30 22:28:13.758  INFO 97564 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1165 ms
2020-11-30 22:28:14.064  INFO 97564 --- [           main] o.a.c.w.s.f.ReflectionServiceFactoryBean : Creating Service {http://soap.ws.ckranz.com/}BankingServiceImplementationService from class com.banking.BankingPortType
2020-11-30 22:28:14.145  WARN 97564 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpoint' defined in class path resource [com/ckranz/ws/soap/config/WebServiceConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.xml.ws.Endpoint]: Factory method 'endpoint' threw exception; nested exception is javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException
2020-11-30 22:28:14.148  INFO 97564 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-11-30 22:28:14.158  INFO 97564 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-11-30 22:28:14.164 ERROR 97564 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'endpoint' defined in class path resource [com/ckranz/ws/soap/config/WebServiceConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.xml.ws.Endpoint]: Factory method 'endpoint' threw exception; nested exception is javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]

Here is some code:
https://www.codepile.net/pile/Ym773bm2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Group and select last insert in a table I've a table to save some file with a simple versionning system like :
ID | FILENAME | CONTENT | DATE
1 | index.php | Content of index.php v1 | timestamp
2 | main.css| Some CSS content | timestamp
3 | index.php | Content of index.php v2 | timestamp

I need to code a SQL request to find in this table the last inserted content of each file.
For this, I tried to group and order by date but with this request :
SELECT * FROM modeles GROUP BY filename ORDER BY date DESC

but it didn't work because the order is done after the group and because the group take the first entry.
If someone here know the solution (this is probably easy but i don't know how to do...).
Thank you.

A: You can use a Subquery
SELECT ID, FILENAME, CONTENT, DATE
FROM TABLE AS Main
WHERE ID = (SELECT MAX(Sub.ID) FROM TABLE AS Sub WHERE Sub.FILENAME = Main.FILENAME)

Optional WHERE if ID is not always the high on the last edited one_
WHERE DATE = (SELECT MAX(Sub.DATE) FROM TABLE AS Sub WHERE Sub.FILENAME = Main.FILENAME)


text:
Q: What is the value of OOP in ASP.NET MVC? As a C++ developer from the 90s during the great OOP wars, I put high value to OOP as a basis for hiring new C# developers into the company.
However, there are plenty of frameworks today like ASP.NET MVC that handles most of the OOP heavy lifting. Programmers without deep knowledge of OOP can just as easily follow the paradigm and still be able to complete their projects. OOP may not be as compelling as it was before for us application developers, especially with a framework like MVC.
I can see a few instance where OOP will be really handy, like for example developing a workflow type of a project. Or those with state-machine requirements. But really, most projects that really come by (at least to us here anyway) are just CRUD functionalities.
Below is my list when hiring. Is it fair to have OOP there as the number one item?

*

*OOP and Design

*Server side programming: C#, ASP.NET MVC and EF

*Client side programming: JQuery, CSS, HTML, etc.

*Database design

A: OOP-thinking indicates, that candidate is good at project-architecture. You always need to implement some reusable components, classes, functions, and of course libraries. From my point of view, it is must have for any candidate to know OOP and Design Patterns to be hired.


text:
Q: Ruby initialize In the example below (source),
class Greeter
  def initialize(name = "World")
    @name = name
  end
  def say_hi
    puts "Hi #{@name}!"
  end
  def say_bye
    puts "Bye #{@name}, come back soon."
  end
end

*

*What is def initialize(name = "World") doing?

*What is @name = name doing? Is it initializing the variable name and setting the initial value to be name?

I do not see any use of "World" anywhere further as I follow the example from the site (more code), hence my confusion on it's use.

Now let's create a greeter object and use it:
greeter = Greeter.new("Pat")
greeter.say_hi
# => Hi Pat!
greeter.say_bye
# => Bye Pat, come back soon.

A: It's important to understand the difference between instance variables like @name and local variables like name. They're not the same, but can be easily confused.
The initialize function is best explained as this:
# Define an initialize method with an argument called name that has
# a default value of "World"
def initialize(name = "World")
  # Assign the value of the name variable, which only exists in the
  # scope of this method, to the name instance variable which exists
  # for the lifespan of this Greeter object.
  @name = name
end

Instance variables are the backbone of Ruby's object oriented programming. They're the most convenient method to persist data between different method invocations.
To exercise the default behaviour you simply fail to specify what name should be:
greeter = Greeter.new
greeter.say_hi

A:

1. What is def initialize(name = "World") doing?

When you create a new instance of Greeter, if no argument is passed then def initialize sets the default @name attribute of your new instance to equal "World".

2. What is @name = name doing? Is it initializing the variable name and setting the initial value to be name?

@name is an instance variable which other methods from the same class can see and use. In this case it takes the name parameter that is passed to the method. See instance variables for more information.
Example
In your example greeter = Greeter.new("Pat"), the argument is defined as"Pat" so the default argument of "World" is ignored.


text:
Q: Upgrading the JRE used by ColdFusion I have a ColdFusion 8.1 application. It gets heavy use and I see jrun.exe getting very high memory usage in the task manager. This is a 32-bit windows 2003 server. When Jrun gets around a gig of memory usage ColdFusion will stop responding at some point. The logs are a little vague, but I start to see garbage collection and heap errors in the ColdFusion log. I assume that the JRE is running out of memory.
I have the max JVM heap set to 1.2gig. After some experimenting, this seemed to be the biggest amount I could allocate and still have ColdFusion start ok. I realize that going to 64-bit might solve the problem, but that is not an option at this time.
I am considering upgrading the JRE (it is at v6.x dated pre-2008, though I don't know the exact version. I am using the JRE that came with ColdFusion 8.1. Has anyone gone through this? I assume it's just a matter of installing the new JRE and pointing ColdFusion to the new JRE directory in the ColdFusion server settings.
tia
don

A: it's EXTREMELY easy to do.
1) download the Java SE Development Kit and install it like normal.
2) open up the jmv.config for cf in a text editor, located in c:\coldfusion8\runtime\bin
3) comment out the existing java.home line with a by putting a "#" at the beginning of the line add a new java.home line below it pointing to your jvm installation.
As an example, my java.home and jvm.config look like this:
java.home=C:/Program Files/Java/jdk1.6.0_11/jre
4) restart the CF services.
As a bonus, you can running JavaRa and free up some space by deleting all the old versions of the JRE.

A: Adobe has a Knowledge Base that covers issues like this. Check out http://www.adobe.com/go/2d547983 for instructions.
Sean Corfield has an article that provides some info on using Java 6 with ColdFusion 8 here:
http://corfield.org/blog/index.cfm/do/blog.entry/entry/Java_6_and_ColdFusion_8
As long as you install 1.6.0_10 or greater, you should be fine. You might check out ColdFusionBloggers.org from time to time in case other JVM issues come to light in the future.

A: You didn't specify whether or not you were using the stand-alone server instance or a multi-server configuration. If you're getting a heavy volume of traffic and have a dual core machine with a lot of physical memory, I would consider looking into the multi-server set-up for CF8 and putting together a cluster with load balancing. This will help to distribute your traffic across several instances of CF8 and, assuming you have a beefy server, make better use of the physical resources that you have available.
-Rick

A: Consider moving Java 7. Java 7 has the G1 Garbage collector which is better at memory deallocation.

If you are having out of memory issues it could be because

*functions are not using var or local scope

*<cfdump> is used in a production system

*Sessions are too large or are not set to expire in a reasonable amount of time

*Queries are way too large SELECT * can cause that.

*Excessive number Query of Queries.

*The site is connecting to a slow database. Resources are held until the DB returns data

*DSN has the data buffer set to more than 64k


text:
Q: C++ macOS M1 ld: symbol(s) not found for architecture arm64 clang: error i have a project about sorting data from files. However when i tried to implement main.cpp, i got an error.
TERMINAL OUTPUT:

*

*Executing task: /usr/bin/clang++ -std=c++17 -stdlib=libc++ -g /Users/utku/Desktop/workspaces/cppworkspace/homework-1/main.cpp -o /Users/utku/Desktop/workspaces/cppworkspace/homework-1/main

Undefined symbols for architecture arm64:
"TestBed::setAlgorithm(int, int)", referenced from:
_main in main-f84827.o
"TestBed::execute()", referenced from:
_main in main-f84827.o
"TestBed::TestBed()", referenced from:
_main in main-f84827.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

*

*The terminal process "/bin/zsh '-c', '/usr/bin/clang++ -std=c++17 -stdlib=libc++ -g /Users/utku/Desktop/workspaces/cppworkspace/homework-1/main.cpp -o /Users/utku/Desktop/workspaces/cppworkspace/homework-1/main'" terminated with exit code: 1.

*Terminal will be reused by tasks, press any key to close it.

(Using VSCode and M1 MacBook) ,
¨
using namespace std;
int main(int argc, char *argv[]) {
string testfile;

if (argc < 2) {
    cout << "Enter a test file name:" << endl;
    cin >> testfile;
}
else {
    testfile = argv[1];
 }

 ifstream file(testfile.c_str());
 if (file.is_open()) {
    cin.rdbuf(file.rdbuf());
}
 else {
    cout << "Error: cannot read the test file!" << endl;
    return -1;
 }

 int algorithmType = 0;
 int k = 0;

 // Numbers are obtained from the file line by line with cin
 cin >> algorithmType;
 cin >> k;

 // Create a TestBed object, initialize and execute the algorithm
 TestBed *test = new TestBed() ;
 test->setAlgorithm(algorithmType,k);
 test->execute();

 return 0;

}¨


text:
Q: Custom CSS in UIWebView So in my iPad app, i'm hoping to add a custom Twitter feed using UIWebView but wanted to use a custom CSS file
Is this possible?
if so how would i go about do it?
Cheers

A: You can forcefully inject javascript into a UIWebView at any time, modifying the underlying HTML. You can either use basic javascript or, if a library like jQuery is loaded, use it:
[webView stringByEvaluatingJavaScriptFromString:@"$('.className').css('color','#f00')"];

You can also load entire scripts and modify, add, delete  tags -- you just have to write the javascript to accomplish the changes.

A: You can get the DOMDocument from the webview,, and then add the css to it that way.
DOMDocument* domDocument=[webView mainFrameDocument];
DOMElement* styleElement=[domDocument createElement:@"style"];
[styleElement setAttribute:@"type" value:@"text/css"];
DOMText* cssText=[domDocument createTextNode:@"body{font-weight:bold;}"];
[styleElement appendChild:cssText];
DOMElement* headElement=(DOMElement*)[[domDocument getElementsByTagName:@"head"] item:0];
[headElement appendChild:styleElement];


text:
Q: Multiple Domains for the same Meteor App - how to get the URL I need to serve a meteor-app on several domains (e.g. customer1.com and customer2.com) and based upon which domain it runs on, it should serve different css files and change its behaviour a little.
I use nginx as a proxy to forward all incoming traffic (except for some special subdomains) to this webapp.
(how) is it possible to get the URL, over which the app is accessed inside of meteor?

A: If you're using iron-router you can get the host from the request object
Router.route('/testHost', function() {
  this.response.end(this.request.headers.host);
  //the page will print out something like 127.0.0.1:3000
}, {where: 'server'});


text:
Q: Show complete documentation in vscode Jupyter Notebook shows the complete documentation on shift + tab.
Is there a way I can get the same with vscode?
Ctrl + shift + space only provides methods signature.
Edit: I am hoping to see something like this

A: I have recently been trying to get to use VSCode with Jupyter Notebooks as well and for me (on macOS, I assume it would be the same for Windows) all I have to do is hover the mouse on top of the method I wanna get the documentation for and wait a little bit, and it'll pop up.
Please take a look at the image below (since this is my first answer I can't embed the picture, but you should be able to click the link to have a look).

A: You could try to use the extension: Pylance.
If you want to view related information, you could find it in the folder under the module that you need to install in the created virtual environment.
For example, using the module 'pandas', you can find file 'parsers.py' in '.venv\Lib\site-packages\pandas\io', which contains relevant parsed content.

Reference: https://marketplace.visualstudio.com/items?itemName=ms-python.python

A: I have the same problem. The only solution I found is to use "?" at the end of the function like,
np.random.randint? run

A: Just started using the Docs View extension, and it is awesome!
https://marketplace.visualstudio.com/items?itemName=bierner.docs-view
It puts the documentation you usually see on hover in the side panel. (I learned about it from this tweet)

Works in the notebook view, too!

A: As Caner Erden pointed out, you can use Pythons base functionality of typing a '?', just make sure you do it before the method, not after.
This will give you the complete documentation you are looking for, just within the code cell, unfortunately not a pop out window like Jupyter Notebook.
Example of documentation in vscode-jupyter
This contextual help issue is being tracked here on vscode-jupyter GitHub.

A: Sometimes I can't read all the lines; so I click the method then shift f12 open definition to the side.  Then if I hover, I can read all the lines.


text:
Q: Is there any way that could help me select specific data from table in Microsoft.AspNetCore.Datasync.EFCore Am learning about data sync from API to WPF app. Got a demo from https://github.com/Azure/azure-mobile-apps/tree/main/samples. But I got into a problem that all the data inside the tables are collected on the call but I need to select specific data using Id. Tried a query etc all came to nothing. Please guide me
Thank you
PatientsController.cs
[Route("tables/Patients")]
public class PatientsController : TableController<Patients>
{
    public PatientsController(AppDbContext context)
        : base(new EntityTableRepository<Patients>(context))
    {

    }
}

AppDbContext.cs
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }
    public DbSet<Patients> Patients => Set<Patients>();
}

A: Try to use the following code:
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }
    public DbSet<Patients> Patients {get;set;}
}

controller:
[Route("tables/Patients")]
public class PatientsController : TableController<Patients>
{
    private readonly AppDbContext _context;
    public PatientsController(AppDbContext context)
        : base(new EntityTableRepository<Patients>(context))
    {
        _context=context;
    }
    public async Task<IActionResult> Index(int id){
         var Patients=_context.Patients.FindAsync(id);
         return View(Patients);
    }
}

A: If you just need to get a record by Id, you use the URL https://mysite/tables/myTable/id - no search required - it will go directly to the entity you want.
If you need to limit what a user can see, you will need to implement an access control provider (which is an implementation of IAccessControlProvider).  This provides three methods to limit what a user can see and do model updates for ensuring the write operations store the right thing.  You can read more here: https://learn.microsoft.com/en-us/azure/developer/mobile-apps/azure-mobile-apps/howto/server/dotnet-core#configure-access-permissions
If it's something else, you'll need to be a little more specific.  I hang out in the issues and discussions of the azure/azure-mobile-apps repo, so feel free to file a question there.


text:
Q: Access to ubuntu based server by web browser with GUI I am thinking about building home server based on Ubuntu (I don't have much experience in Unix systems). I would like to use it because I want to have trustworthy system for my use and keep my private data safely on other disks (zfs pool).
My question is can I install f.ex Ubuntu Server Edition and install GUI to it (Budgie, etc) or some webGUI. After that have access to this server remotely from other home pc by web browser and have normal graphical interface in it ( to have "ubuntu desktop inside browser") Is it possible or only option is f.ex remote web access by Cockpit and remote desktop acces by installing VNC Server and connecting by Viewer? I am asking because I will have server placed in home server room without monitor and I would like to have acces to it and use it like normal computer (also away from home by service like dyndns or simillar).

A: If you meant sharing the desktop (which will enable you to access remotely)
this post has interesting suggestions
Share Desktop via Web Browser


text:
Q: English Grammar: When+past simple
Can you please explain me how can 'shone' be after 'when' ?
Or another example. When added to a liquid,antifreeze lowers the freezing temperature of that liquid'

A: This is best understood as ellipsis - when shone is essentially a shortened version of when it is shone, with the pronoun referring to the subject of the principle verb. You simply need to insert the appropriate pronoun and form of to be. For example:

When stood straight, I am 5'11" tall.
  When I am stood straight, I am 5'11" tall.
When hungry, the dinosaur could eat twice its own bodyweight in a day.
  When it was hungry, the dinosaur could eat twice its own bodyweight in a day.
When angry, Bob had a mad gleam in his eyes.
  When he was angry, Bob had a mad gleam in his eyes.

A: Not simple past but the past participle.
Compare

When eaten too quickly, ice-cream can give you "brain-freeze".

With many verbs the simple past and past participle look the same.

A: "Shone" here is not being used as the simple past, but rather as a perfect participle.

It shines through a prism, a beam of light breaks ...

is wrong because "when" is missing. Without the "when," the intended connection between event and result is not specified. So

It is shone through a prism, a beam of light breaks...

is wrong for the same reason.

When shines through a prism, a beam of light breaks ...

is wrong because "when" coupled with a verb forms a subordinate clause that requires a subject. We see the correct form in

When it is shone through a prism, a beam of light breaks ...

Here we have a subject, the pronoun "it" referring to "beam of light," and a verb in the present tense, namely "is shone." Verbs in the passive voice are constructed through some form of the verb "be" used as a modal plus the perfect participle of substantive verb. In that case, the tense is indicated by the modal. So "is" creates a present tense for the verb in the passive voice.
However

When shone through a prism, a beam of light breaks ...

also is correct because the participle "shone" is being used as an adjective to modify "beam of light." (Alternatively, as pointed out in another answer, it can also be interpreted as an ellipsis.)
The past perfect participle for most verbs can be used by itself to form the simple past in the active voice, with a modal to form verbs in the passive voice for any tense, and as an adjective.
EDIT: There are two subtleties that I have somewhat skipped over. One is why the passive voice is somewhat preferable to the active voice in this particular case. The other is the difficulty of explaining when an ellipsis is permitted in English. That latter reason is why I prefer interpreting the correct answer as the adjectival use of the participle. But that is a matter of pedagogical preference, nothing more.


text:
Q: Gather data cyclically from OPC server I want to acquire historical data cyclically from an OPC server every few minutes. Should I create a separate thread at the client end for the purpose or use some kind of subscription ?

A: Subscriptions are for real-time data.
Historical data is read via the HistoryRead service, which you would indeed need to call periodically.
But why would you read historical data cyclically instead of once at the start followed by receiving live updates for the values you're interested in? Or at least read the historical data much further apart than every few minutes?


text:
Q: Django TastyPie Resource Update Error I am updating a Django model using tastypie API from a mobile client using JQuery.
When I send the PUT request, I get the error that Column 'created' cannot be null.
The 'created' column is in my model to be updated which is of type
models.DateTimeField(auto_now_add=True).

When updating using tastypie API, the update causes this column to be set to null which throws an error.
The model can be successfully updated using django form directly. The error is caused only from the API update call. Not sure what could be the issue.
I tried changing the field to (default=datetime.datetime.now, editable=False, blank=True)
in place of auto_now_add but still it gave the same error. Let me know if anybody knows what the issue could be.
Here is part of the resource code:
class AbcResource(ModelResource):

    def obj_update(self, bundle, request=None, **kwargs):
        logger.debug("Update called")
        res = super(AbcResource, self).obj_update(bundle, request)
        signals.abc_updated.send( sender=request, abc=res.obj, user=request.user )
        return res

Here is part of the model:
class Abc( models.Model ):
    created = models.DateTimeField(_('created'), auto_now_add=True)

There is no custom save method for the model.
Hers is the code to send the PUT request:
var url = root + "/api/v1/abc/" + selected_abc + "/" + "?user_key=" + user_guid + "&user_name=" + username + "&format=json";
var abc_data = xmlRequest(url, false);
abc_data["field"] = field_value;
var request = $.ajax({
                     url: url,
                     type: 'PUT',
                     contentType: 'application/json',
                     data: JSON.stringify(abc_data),
                     dataType: "application/json",
                     processData: false
                     })
request.done(function(msg) {
             console.log("Status update pass : " + msg);
             });

request.fail(function(jqXHR, textStatus) {
             console.log("Status update fail : " + jqXHR.responseText);
             console.log(jqXHR);
             });

Is more information required?

A: Is there other fields than your DateTimeField in you model? using the PUT command will change completely your data, so you need a complete entry.
If you want to partially update a field try the PATCH command
http://django-tastypie.readthedocs.org/en/latest/interacting.html#partially-updating-an-existing-resource-patch


text:
Q: Intuition behind f-related vector fields Let $f: M \mapsto N $ be a smooth map between differentiable manifolds. Then a vector field $X$ on $M$ is f-related to a vector field $Y$ in N if $$(f_*)_p (X_p) = Y_{f(p)} \ \ \forall p \in M$$
That is the derivative of the map $f$ at $p$ acting on a tangent vector at $p$ of $X$ is equal to a tangent vector at $Y$ at $f(p)$.
I'm struggling to understand the intuition behind this definition. How should one think about this? Is there a geometric interpretation?

A: Concretely, if $X$ is a vector field on $M$ and if $f : M \to N$ is an injective smooth map, then $\mathrm{d}f(X) = f_*X$ is a "vector field" on $f(M) \subset N$. $f(M)$ may not be a submanifold or anything, so it is not a "real" vector field. But if you can extend it in $N$, that is, if there exists a vector field $Y$ such that $f*X = Y$ at each $f(p) \in N$, then you say that $Y$ is $f-$related to $X$.
This definition is here to work with images of vector field by smooth maps as if they were "true" vector fields on $N$. Sometimes, one can not extend it (think of the tangent vector field of a self-crossing cuve in the plane).
Note that I asked $f$ to be injective, but one can just ask that if $f(p) = f(q)$, then $\mathrm{d}f(p)X_p = \mathrm{d}f(q)X_q$ so that the value of $f_*X$ at a point $z \in f(M)$ would not depend on the point in $f^{-1}(z)$.


text:
Q: How to select date in different timezone? I want to convert date to (Africa/Cairo) timezone in query result according to it's time zone stored in db
for example I want to get (s_start) and convert it from (Europe/London)to (Africa/Cairo) but in the select query itself(because I print event date from query result event.start).
My controller:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class EventCalendar_model extends CI_Model {

function get_event_list() {
$aa = ($this->session->userdata(id));

$this->db->select('s_timezone,u_name,s_id,s_student,s_tutor,
UNIX_TIMESTAMP(s_start)*1000 as start ');
$this->db->select('s_start as start');

$this->db->from('sessions');
$this->db->where("s_tutor", $aa );

$this->db->join('users', 'sessions.s_student = users.u_id');

$query = $this->db->get($this->event);

    if ($query) {
        return $query->result();

    }
    return NULL;
  }

}

A: Hope the below Query will help you.
SELECT UNIX_TIMESTAMP(CONVERT_TZ(`s_start`, '+02:00', @@session.time_zone)) as africa_cario_time FROM `table_name`


text:
Q: Handling referenced objects from JSON Objects I am using Jackson as a mapper for a REST Service. A sample json response is
{
   "id": 1,
   "name": "One fine name",
   "child": 1 //this is a primary key referencing a composite object
}

Now, using Jackson to map this notation into POJOs, the class would probably look like the following
class Parent{
    protected Integer id;
    protected String name;
    protected Child child;

    //....
    //appropriate Getters and Setters
}

But when Jackson is about to deserialize the object, it complains about converting an integer into the Child object. Any idea how to make Jackson understand that the value for the child field is a reference?


text:
Q: react firebase image post 400 error on uploading I am trying to upload an image to a cloud storage and received an post 400 error
The file is in initialize in another component.
Thanks for help
const projectStorage = getStorage();

useEffect(() => {

    const storageRef = ref(projectStorage, file.name);

    uploadBytes(storageRef, file).then((snap) => {
        let percentage = (snap.bytesTransferred / snap.totalBytes) * 100;
        setProgress(percentage);
        console.log('File Uploaded');
    }, (err) => {
        setError(err);
    }, async () => {
        //this url doesnt change the setstate url becuase it is in seperate score
        const url = await storageRef.getDownloadURL();
        setUrl(url);
    })

}, [file]);

A: I created a new project on firebase and then change the permissions on the storage rules and its works.


text:
Q: Uncaught Typeerror in Bundled Code for Angular 2 Using Gulp First off - thanks for your help! I've built a web app using Angular 2 and am in the final process of launching in production, but am experiencing an error in bundling with Gulp. There seems to be a lot of documentation around the specific Typeerror I'm experiencing, but nothing that I've seen really matches my use case and position in the process.
Specifically, the actual bundling process itself returns no errors when running the following command:
sudo gulp

However, when validating whether the code can run on my localhost, the following error is returned:
Uncaught TypeError: Cannot read property 'prototype' of undefined

and the file where this error is referenced is app.min.js, which is the output file of my wholly bundled code.
After debugging the issue further, from what I can tell, there's potentially some disconnect in how modules are being evaluated, but I can't seem to put a thumb on the root cause of the issue, or a solution to the issue. That's where I could use the community's help - figuring out how to address the issue where 'prototype' cannot be read.
gulpfile.js:
const gulp = require('gulp');
const del = require('del');
const cleanCSS = require('gulp-clean-css');
const concat = require('gulp-concat');
const liveServer = require('gulp-live-server');
const plumber = require('gulp-plumber');
const runSequence = require('run-sequence');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const sysBuilder = require('systemjs-builder');
const tslint = require('gulp-tslint');
const tsc = require('gulp-typescript');
const uglify = require('gulp-uglify');
const tsconfig = require('tsconfig-glob');

const tscConfig = require('./tsconfig.json')

// Development

gulp.task("devmin", function () {
    return gulp.src([
        'wwwroot/js/jquery.js',
        'node_modules/core-js/client/shim.js',
        'node_modules/zone.js/dist/zone.js',
        'node_modules/reflect-metadata/Reflect.js',
        'wwwroot/js/toastr.js',
        'wwwroot/js/moment.js',
        'wwwroot/js/typescript.js',
    ])
    .pipe(concat('site.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('wwwroot/js'));
});

// Clean the distribution directory

gulp.task('clean:dist', function() {
    return del('wwwroot/dist/*');
 });

// Clean the JavaScript distribution directory

gulp.task('clean:dist:js', function() {
    return del('wwwroot/dist/js/*');
 });

// Clean the CSS Distribution directory

gulp.task('clean:dist:css', function() {
    return del('wwwroot/dist/css/*');
 });

 // Clean library directory

gulp.task('clean:lib', function () {
  return del('wwwroot/lib/**/*');
 });

// Compile TypeScript to JS

gulp.task('compile:ts', function () {
  return gulp
    .src(tscConfig.filesGlob)
    .pipe(plumber({
      errorHandler: function (err) {
        console.error('>>> [tsc] Typescript compilation failed'.bold.green);
        this.emit('end');
      }}))
    .pipe(sourcemaps.init())
    .pipe(tsc(tscConfig.compilerOptions))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('wwwroot/dist/app'));
});

// Generate SystemJS-based builds

gulp.task('bundle:js', function() {
  var builder = new sysBuilder('wwwroot', 'wwwroot/systemjs.config.js');
      console.log("-----------------------------Start");
  return builder.buildStatic('app', 'wwwroot/dist/js/app.min.js')
    .then(function () {
      console.log("-----------------------------Deleting");
      return del(['wwwroot/dist/js/**/*', '!wwwroot/dist/js/app.min.js']);
    })
    .catch(function(err) {
      console.error('>>> [systemjs-builder] Bundling failed'.bold.green, err);
    });
});

// Minify JS bundle

gulp.task('minify:js', function() {
  return gulp
    .src('wwwroot/dist/js/app.min.js')
    .pipe(uglify())
    .pipe(gulp.dest('wwwroot/dist/js'));
});

gulp.task('compile:sass', function() {
    // concat and minify global scss files
    gulp
        .src('wwwroot/css/global/*.scss')
        .pipe(plumber({
            errorHandler: function (err) {
                console.error('>>> [sass] Sass global style compilation failed'.bold.green);
                this.emit('end');
            }}))
        .pipe(sourcemaps.init())
        .pipe(sass({ errLogToConsole: true }))
        .pipe(concat('styles.min.css'))
        // .pipe(cleanCSS())
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('wwwroot/dist/css/global'));

    // minify component specific scss files

    gulp
        .src('wwwroot/css/*.scss')
        .pipe(plumber({
            errorHandler: function (err) {
                console.error('>>> [sass] Sass component style compilation failed'.bold.green);
                this.emit('end');
            }}))
        .pipe(sourcemaps.init())
        .pipe(sass({ errLogToConsole: true }))
        // .pipe(cleanCSS())
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('wwwroot/dist/css/component'));
});

// Concat and minify CSS

gulp.task('minify:css', function() {
    // concat and minify global css files
  gulp
    .src('wwwroot/css/*.css')
    .pipe(concat('styles.min.css'))
    .pipe(cleanCSS())
    .pipe(gulp.dest('wwwroot/dist/css'));

        // minify component css files

  gulp
    .src('wwwroot/css/component/*.css')
    .pipe(cleanCSS())
    .pipe(gulp.dest('wwwroot/dist/css/component'));
});

// Copy dependencies

gulp.task('copy:libs', function() {
    gulp.src([
        'node_modules/rxjs/**/*'
    ])
    .pipe(gulp.dest('wwwroot/lib/js/rxjs'));

    gulp.src([
        './node_modules/reflect-metadata/Reflect.js',
        './node_modules/zone.js/dist/zone.js',
        './node_modules/core-js/client/shim.js',
        '.node_modules/systemjs/dist/system.src.js',
        './node_modules/bootstrap/dist/js/bootstrap.js',
        './node_modules/jquery/dist/jquery.js',
        './node_modules/moment/moment.js',
        './node_modules/es6-promise/dist/es6-promise.js',
        './node_modules/typescript/lib/typescript.js',
        './node_modules/systemjs/dist/system.src.js',
        './node_modules/toastr/package/toastr.js'
    ])
    .pipe(gulp.dest('wwwroot/lib/js'));

    gulp.src([
        './node_modules/jquery/dist/jquery.min.js',
        './node_modules/bootstrap/dist/js/bootstrap.min.js',
        './node_modules/es6-promise/dist/es6-promise.min.js',
        './node_modules/toastr/toastr.js',
        './node_modules/moment/min/moment.min.js',
        './node_modules/angular-in-memory-web-api/dist/index.js',
        './wwwroot/systemjs.config.js'
    ])

    .pipe(concat('vendors.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('wwwroot/lib/js'));

      // copy source maps
    gulp.src([
        './node_modules/es6-shim/es6-shim.map',
        './node_modules/reflect-metadata/Reflect.js.map',
        './node_modules/systemjs/dist/system-polyfills.js.map'
    ]).pipe(gulp.dest('wwwroot/lib/js'));

    gulp.src([
        '.node_modules/bootstrap/dist/css/bootstrap.*',
        './node_modules/bootstrap-toggle/css/bootstrap-toggle.css',
        './node_modules/bootstrap/dist/css/bootstrap-theme.css',
        './node_modules/bootstrap/dist/css/bootstrap-theme.css.map',
        './node_modules/bootstrap-social/bootstrap-social.css',
        './node_modules/font-awesome/css/font-awesome.css.map',
        './node_modules/font-awesome/css/font-awesome.css',
        './node_modules/glyphicons-halflings/css/glyphicons-halflings.css.map',
        './node_modules/glyphicons-halflings/css/glyphicons-halflings.css',
        './node_modules/toastr/package/toastr.css',
        './node_modules/toastr/package/toastr.css',
    ]).pipe(gulp.dest('wwwroot/lib/css'));

    gulp.src([
        "./node_modules/font-awesome/fonts/FontAwesome.otf",
        "./node_modules/font-awesome/fonts/fontawesome-webfont.eot",
        "./node_modules/font-awesome/fonts/fontawesome-webfont.svg",
        "./node_modules/font-awesome/fonts/fontawesome-webfont.ttf",
        "./node_modules/font-awesome/fonts/fontawesome-webfont.woff",
        "./node_modules/font-awesome/fonts/fontawesome-webfont.woff2",
        "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.eot",
        "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.svg",
        "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.ttf",
        "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.woff",
        "./node_modules/bootstrap/fonts/glyphicons-halflings-regular.woff2"
    ]).pipe(gulp.dest('wwwroot/dist/fonts'));

    gulp.src(['./node_modules/angular-in-memory-web-api/**/*']).pipe(gulp.dest('wwwroot/lib/js/angular-in-memory-web-api'));

    // handle all angular

    return gulp.src(['node_modules/@angular/**/*'])
        .pipe(gulp.dest('wwwroot/lib/js/@angular'));
});

// Copy static assets

gulp.task('copy:assets', function() {
    return gulp.src(
        [
            '*.json',
            '*.html',
            '*.css',
            '!*.ts',
            '!*.scss'
        ],
            { base: '' })
            .pipe(gulp.dest('wwwroot/dist'))
});

// Update the tsconfig files based on the glob pattern

gulp.task('tsconfig-glob', function() {
    return tsconfig({
        configPath: '.',
        indent: 2
    });
});

// Watch the source files for changes, then trigger recompilation

gulp.task('watch:src', function() {
    // gulp.watch('src/**/*.ts', ['scripts']);
    // gulp.watch('src/**/*.scss', ['styles']);
    gulp.watch('./**/*.ts', ['scripts']);
    gulp.watch('./**/*.scss', ['styles']);
});

gulp.task('test', ['compile:specs'], function() {
    // gulp.watch('src/**/*.ts', ['compile:specs']);
    gulp.watch('./**/*.ts', ['compile:specs']);
});

gulp.task('lint', ['lint:sass']);

// gulp.task('clean', ['clean:dist:js', 'clean:dist:css', 'clean:lib']);

gulp.task('copy', function(callback) {
//    runSequence('clean:lib', 'copy:libs', callback);
    runSequence('copy:libs', callback);
});

gulp.task('scripts', function(callback) {
    // runSequence(['clean:dist:js'], 'compile:ts', 'bundle:js', 'minify:js', callback);
    runSequence('compile:ts', 'bundle:js', 'minify:js', callback);
});

gulp.task('styles', function(callback) {
//    runSequence(['clean:dist:css'], ['compile:sass', 'minify:css'], callback);
    runSequence(['compile:sass', 'minify:css'], callback);
});

gulp.task('build', function(callback) {
    runSequence('copy', 'scripts', 'styles', callback);
});

gulp.task('buildnocopy', function(callback) {
    runSequence('scripts', 'styles', callback);
});

gulp.task('default', function(callback) {
    runSequence('build', callback);
});

systemjs.config.js:
// map tells the System loader where to look for things
var map = {
  'app': 'dist/app',
  'rxjs': 'lib/js/rxjs',
  '@angular': 'lib/js/@angular',
  'zone.js': 'lib/js/zone.js',
  'moment': 'lib/js/moment',
  'angular-in-memory-web-api': 'lib/js/angular-in-memory-web-api',
  'typescript': 'lib/js/typescript',
};

// packages tells the System loader how to load when no filename and/or no extension
var packages = {
  'app': { main: 'main', defaultExtension: 'js' },
  'rxjs': { defaultExtension: 'js' },
  'zone.js': { main: 'zone', defaultExtension: 'js' },
  'symbol-observable': { main: 'index.js', defaultExtension: 'js' },
  'angular-localstorage': { defaultExtension: "js"},
  "angular-in-memory-web-api": { main: "index.js", defaultExtension: "js" },
  'moment': { defaultExtension: 'js' }
};

var packageNames = [
  '@angular/common',
  '@angular/compiler',
  '@angular/core',
  '@angular/forms',
  '@angular/http',
  '@angular/platform-browser',
  '@angular/platform-browser-dynamic',
  '@angular/router',
  '@angular/testing',
  '@angular/upgrade',
];

// add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
  packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});

System.config({
  map: map,
  packages: packages
});

tsconfig.json:
{
  "compileOnSave": true,
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "module": "system",
    "moduleResolution": "node",
    "rootDir": "wwwroot",
    "outDir": "wwwroot/dist",
    "sourceMap": true,
    "target": "ES5",
    "noImplicitAny": false,
    "noEmitOnError": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": [
    "wwwroot/node_modules",
    "node_modules",
    "typings",
    "wwwroot/lib"
  ],
  "filesGlob": [
    "wwwroot/app/**/**/*.ts",
    "typings/*.d.ts"
  ]
}

Please let me know if I need to provide any more documentation. Thanks!

A: I know there was a point where the minification/uglification of Angular 2 with gulp-uglify was broken.
Try removing the uglify step and see if that helps your case.


text:
Q: Find rows not used by xml column I have a status table, and I must find the unused statuses.
The status code can be used in activity templates, which have an actionlist xml column with custom formulas.
So far I have written this, which works, but is incredibly slow (more than a minute to get 5000 lines), and I would need to speed it up a bit.
select *
from [status] s
where not exists (
    select top 1 1
    from Wf_ActivityTemplate at
    where at.actionlist.value('.', 'nvarchar(max)') like '%@GetStatusId("' + s.code + '")%'
)

The actionlist column looks like this (irrelevant nodes removed).
As you can see, I need to search in the //ActionTriplet/Argument node, which is itself an xml node stored in text.
<ArrayOfActionTriplet xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ActionTriplet>
    <Priority>1</Priority>
    <Argument><?xml version="1.0" encoding="UTF-8" standalone="yes"?><string>@SetProp("STATUS",@GetStatusId("INTERNAL DESIGN REVIEW"));True</string></Argument>
    <ActionCode>APPLY_FORMULA</ActionCode>
    <TriggerTaskCode />
    <TriggerTaskIsSecondary>false</TriggerTaskIsSecondary>
    <TriggerTaskConditionFormula />
  </ActionTriplet>
  <ActionTriplet>
    <Priority>2</Priority>
    <Argument><?xml version="1.0" encoding="UTF-8" standalone="yes"?><string>@SetProp("STATUS",@GetStatusId("VALID"));True</string></Argument>
    <ActionCode>APPLY_FORMULA</ActionCode>
    <TriggerTaskCode />
    <TriggerTaskIsSecondary>false</TriggerTaskIsSecondary>
    <TriggerTaskConditionFormula />
  </ActionTriplet>
</ArrayOfActionTriplet>

A: Your code is taking the whole content of your XML, converts it to nvarchar and performs a %x%-like-search, which is always slow. The bigger the text, the slower...
To show another approach I declare a table variable, which mocks up your table, with two rows (see the ID). I search for the code given in @YourCode:
DECLARE @YourCode NVARCHAR(100)=N'INTERNAL DESIGN REVIEW';

DECLARE @YourTable TABLE(ID INT IDENTITY, actionList XML);
INSERT INTO @YourTable(actionList) VALUES(
'<ArrayOfActionTriplet xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ActionTriplet>
    <Priority>1</Priority>
    <Argument><?xml version="1.0" encoding="UTF-8" standalone="yes"?><string>@SetProp("STATUS",@GetStatusId("INTERNAL DESIGN REVIEW"));True</string></Argument>
    <ActionCode>APPLY_FORMULA</ActionCode>
    <TriggerTaskCode />
    <TriggerTaskIsSecondary>false</TriggerTaskIsSecondary>
    <TriggerTaskConditionFormula />
  </ActionTriplet>
  <ActionTriplet>
    <Priority>2</Priority>
    <Argument><?xml version="1.0" encoding="UTF-8" standalone="yes"?><string>@SetProp("STATUS",@GetStatusId("VALID"));True</string></Argument>
    <ActionCode>APPLY_FORMULA</ActionCode>
    <TriggerTaskCode />
    <TriggerTaskIsSecondary>false</TriggerTaskIsSecondary>
    <TriggerTaskConditionFormula />
  </ActionTriplet>
</ArrayOfActionTriplet>')
,(
'<ArrayOfActionTriplet xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ActionTriplet>
    <Priority>1</Priority>
    <Argument><?xml version="1.0" encoding="UTF-8" standalone="yes"?><string>@SetProp("STATUS",@GetStatusId("INTERNAL DESIGN REVIEW"));True</string></Argument>
    <ActionCode>APPLY_FORMULA</ActionCode>
    <TriggerTaskCode />
    <TriggerTaskIsSecondary>false</TriggerTaskIsSecondary>
    <TriggerTaskConditionFormula />
  </ActionTriplet>
  <ActionTriplet>
    <Priority>2</Priority>
    <Argument><?xml version="1.0" encoding="UTF-8" standalone="yes"?><string>@SetProp("STATUS",@GetStatusId("VALID"));True</string></Argument>
    <ActionCode>APPLY_FORMULA</ActionCode>
    <TriggerTaskCode />
    <TriggerTaskIsSecondary>false</TriggerTaskIsSecondary>
    <TriggerTaskConditionFormula />
  </ActionTriplet>
</ArrayOfActionTriplet>');

--This is the query: You'll get back all Argument-elements, where the text within this element contains GetStatusId("TheCode").
SELECT s.ID
      ,arg.query('.')
FROM @YourTable AS s
CROSS APPLY actionList.nodes('/*:ArrayOfActionTriplet/*:ActionTriplet/*:Argument[fn:contains(.,fn:concat("GetStatusId("",sql:variable("@YourCode"),"")"))]') AS A(arg)

UPDATE
With this query you can cast the inner XML from the encoded form to real XML and get the full string readable:
SELECT s.ID
      ,arg.query('.')
      ,InnerXml.value('string[1]','nvarchar(max)')
FROM @YourTable AS s
CROSS APPLY actionList.nodes('/*:ArrayOfActionTriplet/*:ActionTriplet/*:Argument[fn:contains(.,fn:concat("GetStatusId("",sql:variable("@YourCode"),"")"))]') AS A(arg)
CROSS APPLY (SELECT CAST(arg.value('.','varchar(max)') AS XML)) AS Casted(InnerXml)

UPDATE 2: Faster, checking the existance only
If you want nothing more, than to check, wether there is an <Argument> containing your code or not, you might do this:
SELECT s.ID
FROM @YourTable AS s
WHERE actionList.exist('/*:ArrayOfActionTriplet/*:ActionTriplet/*:Argument[fn:contains(.,fn:concat("GetStatusId("",sql:variable("@YourCode"),"")"))]') =1

The final =1 means: The string is inlcuded. With =0 you'd get all rows, where this string is not included


text:
Q: render wicket components while submitting form I am trying to update and render components while submitting form using onSubmit of IndicatingAjaxButton. But all the components are getting rendered once onSubmit is completed. Is there any way I can render them while my form is still submitting, say to show an updating progressbar while form is submitting. I want to show progress as each rest call executes.
            This is roughly what I am doing :
public class MyPage {
    Form form;
    int items;
    WebMarkupContainer progressbar = new WebMarkupContainer("progressbar");
    int progress = 0;
    MyData dataItems = new MyData();

    public MyPage() {
        progressbar.setOutpuMarkupId(true);
        items = 5;
        setupForm();
    }

    public void setupForm() {
        form = new Form("form", new CompundPropertyModel(dataItems));
        form.add(new IndicatingAjaxButton("button") {
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                for (int i = 0; i < items; i++) {
                    progress++;
                    progressbar.add(new AttributeModifier("style", "width: " + progress + "%;"));
                    //rest post call goes here
                }
            }
        });
    }

    add(form);
    add(progressbar);

}

//in html page
<div wicket:id="progressbar" id="progressbar" style="width: 0% ; background-color:green;"></div>

A: The best approach for this is to use Wicket Native WebSockets. With IWebSocketRequestHandler you can update Wicket Components and/or send raw text (JSON, HTML) during the long operation. You can push as many times as needed, e.g. to show progress in percentages.
Another, simpler, solution is to use AjaxCallListener#onBeforeSend() callback to make the UI updates with JavaScript before making the Ajax call (the form submit). With this approach you have only one shot, i.e. you can show a loading indicator but you cannot show the current progress.


text:
Q: Bootstrap navbar-fixed-top height How to set up a custom height (for example 40px instead of 50px) for a Bootstrap navbar-fixed-top with CSS code ?
I tried :
.navbar {
   height: 40px;
   min-height: 40px;
}

but then the text elements are not vertically centered in the navbar.
Jsfiddle : http://jsfiddle.net/xg8swcwc/embedded/result/
Note : This question gives its answer with http://getbootstrap.com/customize/, which needs recompiling a CSS with LESS, which is not what is asked here.

A: If I'm understanding your question, and you can't change the default height of the navbar, you need to change the padding of the links contained at the navbar.
 .navbar-nav > li > a{ padding: 0px 15px }

The ´line-height´ of your navbar-brand is 20px. So, if you want to be centered vertically, you need to give the half of this value to padding-top.
So:
.navbar-brand{ padding-top: 10px; }

A: increasing or decreasing the menu items top and bottom padding's will change the height of nav bard
 .navbar-nav>li>a { padding-top: 10px; padding-bottom: 10px; }
 .navbar-brand { padding: 10px 15px; }

According to the height of the logo you can add separate paddings for .navbar-brand class

A: You need to set the padding appropriately.
Here's what I did for a site I made before I learnt LESS:
@media (min-width: 991px) {
    .navbar-nav > li > a, .navbar-brand {
        margin-top: 30px;
        padding-left: 15px;
        padding-right: 15px;
        line-height: 20px;
    }
}

You might want to use margin-bottom as well, and might want to change the values, but you get the idea.


text:
Q: List rows in table with date information I am in the beginning of building a simple absence script for teachers to administrate students.
I need to populate the same list of students in 5 tables. One table for each day of the current week (monday to friday).
I have the following code at the moment
List students SQL query:
SELECT s.student_id, s.student_firstname, s.student_lastname,
 a.student_absence_startdate, a.student_absence_enddate, a.student_absence_type
FROM students s
LEFT JOIN studentabsence a ON a.student_id = s.student_id
WHERE a.student_absence_startdate
 IS NULL OR
  '2012-06-20'
   BETWEEN
a.student_absence_startdate AND a.student_absence_enddate

This query selects all students and joins another table wich is a linking table that holds the absence information for students.
I the populate the code 5 times like this:
<?php
$data = array();
    while ($row = mysql_fetch_array($list_students)) {
    $data[] = $row;
    }
?>

  <?php
  foreach($data as $row){
    $class = "";
    if ($row['student_absence_type'] == 2) {$class = " style='background:#f00;'";}
    else if ($row['student_absence_type'] == 3) {$class = " style='background:#8A2BE2;'";}

        echo "
";
        echo "".$row['student_firstname']." ".$row['student_lastname']."";
        echo "
\n";
   }
   ?>

My question is how I should manage the date functions.
As you can see in my SQL query I have hardcoded the dates. I need it to automatically select the date of wich table the students are listed.
for example:
table > Monday (2012-07-23)
    the user John Doe has absence information in this span, based on the above query. Let's change the background of
table > Tuesday (2012-07-24)
    the user John Doe has no absence information in this span. Just list him.
etc...

I am not expecting you to write my code. I am just curious on how to think. I am fairly new to programming.

A: The most flagrant error I find in your thoughts is that you don't need those five tables. You'll end up repeating and messing data.
You need different tables, from what I've read.
Students
ID, Name, etc..
Classes
class_id, name,
Teachers
Id_teacher, name, etc
TeachersInClass (so you can now which teachers gave a specific class)
id, id_teacher, id_class
Absences
id, id_student, id_class, date
This leaves you a more robust database, and you can play arroud with multiple associations like, which teachers had the most absences in a year... etc etc.
EDIT: Forgot to answer your "real" question.
You can use the PHP DateTime class to manipulate your dates. It's easy to use, and the php.net has a lot of good examples to give you a boost start


text:
Q: Bringing Google search results into Google Sheets using Regex instead of ImportXML I am tracking keywords for Google search results in Google sheets.
When using importXML it looks like I am getting limited for the amount of XML I can import as I am getting #N/A in cells after a certain amount of use.
I found this custom code by @joshbradley that use of custom scripts to use regex instead of XPath which is meant to get around any limitation. Credit to Josh.
Essentially this goes in the script editor:
    function importRegex(url, regexInput) {
  var output = '';
  var fetchedUrl = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
  if (fetchedUrl) {
    var html = fetchedUrl.getContentText();
    if (html.length && regexInput.length) {
      output = html.match(new RegExp(regexInput, 'i'))[1];
    }
  }
  // Grace period to avoid call limit
  Utilities.sleep(1000);
  return unescapeHTML(output);
}

Then you call the script like this
=importRegex("https://example.com", "<title>(.*)<\/title>")

From here, I am trying to adapt the following code taken from GDS (Credit to Tara) that brings in Google search results but use the custom importregex approach above instead of importxml.
=ARRAYFORMULA(REGEXEXTRACT(IMPORTXML("https://www.google.co.uk/search?q="& SUBSTITUTE(B$1, " ", "+") &"&pws=0&gl=UK&num=50", "//h3[@class='r']/a/@href[contains(.,'url')]"), "\/url\?q=(.+)&sa\b"))

Update
Here are two approaches I have tried (second has the array) but neither are working.
=importRegex("https://www.google.co.uk/search?q="& SUBSTITUTE(B$1, " ", "+") &"&pws=0&gl=UK&num=50", "//h3[@class='r']/a/@href[contains(.,'url')]"), "\/url\?q=(.+)&sa\b"))

=ARRAYFORMULA(REGEXEXTRACT(importRegex("https://www.google.co.uk/search?q="& SUBSTITUTE(B$1, " ", "+") &"&pws=0&gl=UK&num=50", "//h3[@class='r']/a/@href[contains(.,'url')]"), "\/url\?q=(.+)&sa\b"))

If it helps I have put a link to a Google sheet with the importregex script working here


text:
Q: strong deformation retract of $T=([0,1]\times\left\{0\right\})\cup(\cup_{\mathbb{Q}\cap[0,1]}(\left\{q\right\}\times[0,q]))$ I have the following problem: Let $\hat{T}$ be the set obtained by reflecting $T$ across the line $x=y$ and translating the result by $(0,-1)$. Now let $X_0=T\cup \hat{T}$ and for $n\in\mathbb{Z}$, let $X_n$ be the set $X_0$ translated by $(n,n)$. Set $X:=\bigcup_{n\in\mathbb{Z}}X_n$.
For reference I include my definitions of (strong) deformation retracts here: A subspace $A\subseteq X$ is a deformation retract of $X$ if $\exists$ a homotopy $F:X\times[0,1]\to X$ s.t. \begin{equation*}
F(X,0)=X,  F(X,1)=A\text{  and  }F(a,1)=a\forall a\in A
\end{equation*}
whereas for a strong deformation retract, the last equation has to hold $\forall t\in [0,1]$.
a) Any point $x\in X$ is a deformation retract of $X$.
b) No point $x\in X$ is a strong deformation retract of $X$.
My ideas/attempts:
a)$X$ has no 'loops' and if one point is on one of the 'spikes' we get from drawing $X$, we can just 'slide it down' and are then on one of the translations of $[0,1]$ and conclude.
b) I want to show that $X$ is nowhere locally path-connected which would then tell me that no $x\in X$ can be a strong deformation retract of $X$. However, considering for example $(0,0)\in X$, I think I could find a locally path-connected neighborhood of it, so I think I am missing something here. Does anybody know how I could resolve my issue?
Any help appreciated!

A: For (a), you have to be a little careful because either you need to contract the "spikes" at different rates or also move the points on the long zigzag line along with them (but then this also needs to "drag along" the points on the spikes). But that's roughly the idea.
For (b), a reasonable intermediate lemma is that if any $X$ deformation retracts to $x \in X$ then $x$ has a basis of contractible neighborhoods in $X$. But the specific $X$ we are dealing with is not locally path connected at any point.


text:
Q: IPv6 LAN to IPv4 with PFsense Is it possible to setup PFsense to do IPv6 to IPv4?
I am setting up an IPv6 LAN for "testing" and also to mess around with and I can't get an IPv6 address from my ISP so I need a way to change IPv6 to IPv4.
Update
Ok I upgraded to the PFsense 2.0 RC1 which has IPv6 support.
Under the "Advanced Settings" there are options for IPv4 NAT encapsulation of IPv6 packets.
There is a checkbox to enable the option and also a entry box that says "IP Address"
What do I enter there?

A: 6to4 needs to know your extern IPv4 address that it should use. This will determine your IPv6 prefix by embedding the IPv4 address in your IPv6 prefix (basically your IPv6 subnet has the information necessary for other IPv6 hosts to find their way back to your IPv4 address via another 6to4 router.
Your ISP must support 6to4, or you must use a public 6to4 router.
PFsense is based on FreeBSD, I don't know PFsense's interface all that well, but I have an Intro to 6to4 for the FreeBSD CLI on my blog.

A: PFsense doesn't support IPv6, and won't until the next version (2.0).

A:
What do I enter there?

You enter the IP address of the 6-to-4 tunnel broker.

A: You enter the IP address of the 6-to-4 tunnel broker.
This is correct, such as hurricane Electric. This is a PAID service.


text:
Q: How do you snapshot test components with actions from Redux connect? I want to snapshot test a react component that dispatches a redux action in its componentDidMount() handler.  The action is given to the component through Redux's connect().
How should I mock the action?
Right now the action is imported in the component (see Newsfeed.js below). So how would I swap it out for a mock action in my test?
I'm using redux-thunk for my async actions, but that shouldn't matter much.
app/components/Newsfeed.js
import React, { Component } from 'react';
import { connect } from 'react-redux';

// An action that makes an async request to get data
import { loadNewsfeedStories } from '../actions/Newsfeed';

class Newsfeed extends Component {
  componentDidMount(){
    this.props.loadNewsfeedStories();
  }

  ...
}

export default connect(state => ({
  stories: state.newsfeed.stories
}),
{
  loadNewsfeedStories
})(Newsfeed)

app/tests/Newsfeed.test.js
import React from 'react';
import { Provider } from 'react-redux';

// This creates a mockStore using my reducers and a saved JSON state.
import { mockStore } from './MockState';

// The component to test
import Newsfeed from '../components/Newsfeed';

test('Newsfeed matches snapshot', () => {
  const wrapper = mount(
    <Provider store={mockStore}>
      <Newsfeed />
    </Provider>
  );

  expect(wrapper).toMatchSnapshot();
});

Possible Solutions

*

*Export the unconnected component, and manually pass in all props & mock actions. Will be a lot of extra coding compared to just using the mockStore & provider.  Also we won't be testing the 'connected' component.

*Use something like Nock? Seems to intercept HTTP calls, so the ajax requests wouldn't actually go anywhere.

*For axios, there is a lib called moxios - https://github.com/mzabriskie/moxios

A: You could try exporting a different connected component, but with a mocked "mapDispatchToProps" function. This way, no action will get through.
But personally, when testing components. I write a mock reducer, these should not change the state but record all dispatched actions (Jests mock functions are very useful for this). This way, you can also test if the correct action is dispatched when clicking a button,...

A: It's a bad idea to test the component, redux store, and mock http requests at the same time because unit tests should be small.
Another option would be to avoid executing business logic in componentDidMount.
Instead of writing
componentDidMount(){
  this.props.loadNewsfeedStories();
}

You can move this logic to the redux module (depends on libs you use).
If you use only redux-thunk without libraries like saga or redux-logic, you can use this https://github.com/Rezonans/redux-async-connect.

but record all dispatched actions

Redux thunks are hard to test. Your mock dispatcher will receive only an array of functions. And you can't verify if a function was created by loadNewsfeedStories() or by someAnotherThunk().


text:
Q: change the plot in matlab When a figure is created in MATLAB ,
Is it possible to change that shape?
Can I make such changes in the figure window?
For example, I want to change the position of some nodes, or change the color of the arrows.
Some angles are large, for example, in my shape
,
the angle between 5, 7 and 12 is enlarged and I want to be smaller.


text:
Q: Disabling the On-screen Keyboard in Windows XP How do I disable the On-screen Keyboard in Windows XP?

A: You should be able to disable it using the Win-U shortcut to bring up the 'Utility Manager', select the on-screen keyboard, and uncheck Start automatically when I log in.
EDIT :
To block OSK.EXE from running, you could find it (%WINDIR%\System32\OSK.EXE), go to Properties | Security, and change the permissions on it to remove the Read and Execute permission from users that you wish to block from using it.
As an alternative, if you wish to block it on a domain, you could use a group policy to do so.

A: Just open up the command prompt and try navigate to the system32 folder of your window as:
c:\Users\username>cd\
c:\>cd windows
c:\windows>cd system32
c:\windows\system32>takeown /f osk.exe //success here represents you now have admin rights to change its permission
c:\windows\system32>cacls osk.exe /e /c /d %username% // this will deny it from every user

Now remove every entry at startup by opening msconfig.exe and also from Registry editor by looking and googling.


text:
Q: Function to count words, from not where expected I am trying to do a function that count words in a string ignoring spaces, dots, comas, etc... so I started with just ignoring simple spaces, so far this works
Select length ('Hello World') - length(REGEXP_REPLACE('Hello World',
'( ){1,}', '')) into NumDePalabras + 1
from dual;

But when trying to make it into a function that gets as parameter a String and return the number or words it isn't working right now the error is FROM keyword not found where expected.
any ideas of how can I get this to work?
 CREATE OR REPLACE Function WCount
       ( txt IN varchar2 )
        RETURN varchar2
    IS
        resul varchar2(100);

    BEGIN

    Select length (txt) - length(REGEXP_REPLACE(txt,
    '( ){1,}', '')) NumDePalabras + 1 from dual;

    RETURN resul;

    EXCEPTION
    WHEN OTHERS THEN
       raise_application_error(-20001,'se ha encontrado un error - '||SQLCODE||' -ERROR- '||SQLERRM);
    END;

A: SQL>     create or replace function countword(txt varchar2) return varchar2 is
  2      resul varchar2(100);
  3      BEGIN
  4
  5      Select (length (txt) - length(REGEXP_REPLACE(txt,'( ){1,}', '')) ) into resul from dual;
  6
  7      RETURN resul+1;
  8
  9      EXCEPTION
 10      WHEN OTHERS THEN
 11         raise_application_error(-20001,'se ha encontrado un error - '||SQLCODE||' -ERROR- '||SQLERRM);
 12      END;
 13  /

Function created.

SQL>


text:
Q: why this code call general template function in GCC? #include<iostream>

using namespace std;

// define the general compare template
 template <class T>
 int compare(const T& t1, const T& t2) {
   cout<< "Common_T"<<endl;
   return 0;

 }
 template<>
 int compare<const char*>( const char * const& s1,
                          const char * const& s2)
 {
    cout<< "Special_T"<<endl;
    return 0;
 }
typedef const char  char6[6];
     template<>
             int compare<char6>(const char6& s1,const char6& s2)
    {
            cout << "Special_Char6_T" << endl;
             return 0;
    }

 int main() {
     int i = compare("hello" , "world");
 }

the result is:
Common_T

My question is: why don't output "Special_Char6_T"???

A: This is the correct template specialization that matches your c strings.
typedef char char6[6];
template<> int compare<char6>(char6 const &s1,char6 const &s2)
{
    cout << "Special_Char6_T" << endl;
    return 0;
}

A: Intuitively, because the dimension of arrays is not part of their type. That dimension matters only for variables and fields. So both
  char hello[6]="hello";

and
  char longstring[] = "a very very long string should be here";

have both the same type char[]
and
 typedef char t1[6];

and
 typedef char t2[];

are aliases for the "same" type.
(You could look at the mangled function names to have a clue)


text:
Q: Django image not showing up in template (not URLs issue) I've added the neccessary elements to the URLs.py.
The image is NOT stored in the database, it's just a background image.
The source of the img folder is 'storiesapp/static/storiesapp/img'
Settings.py (i've been trying different things as shown)
STATIC_URL = '/storiesapp/static/storiesapp/'
STATIC_ROOT = os.path.join(BASE_DIR, "/static/")

STATICFILES_DIRS = [
    "/storiesapp/static/storiesapp/img/",
    "/static/storiesapp/img/",
    "/storiesapp/img/",
    "/img/",
]

STATICFILES_FINDERS =[
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    # full path where all images are stored - os.path will create the directory regardless of the operating system
MEDIA_URL = '/media/'
    #

.URLs.py
from django.conf import settings
from django.conf.urls.static import static

...

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

.
I'm trying all of the following
     <link rel="apple-touch-icon" sizes="76x76" href="./assets/img/image.png">

A: The answer is "".
It was the wrong syntax.
I was able to come to this solution because I realized that my CSS templates, which I can see are working, are also using the static folder so it couldn't be a problem with the way anything is set up.


text:
Q: How to use a computer as a bluetooth headset? I have very little bluetooth expertize. All I want to do is to occasionally be able to use my computer's speakers and microphone for phone conversations. I don't want to use a bluetooth headset.
All tutorials I can find on the Net are either dated for Ubuntu 12.04 at the very latest, or describe the process of connecting to the bluetooth headset.
I have Ubuntu 14.04 64bit Asus N56VZ notebook with built-in bluetooth device, that works well under Ubuntu.
My phone is Nokia 6310i, and is compatible with bluetooth headsets. I know how to connect this phone to the dedicated headset. I just don't know how to connect it to my notebook for the same purpose.

When I initiate connection from my mobile to the notebook, or initiate connection from my notebook to the mobile or just turn off the bluetooth and the mobile altogether I've got the same, list sources (obtained via pactl list sinks and pactl list sources and filtering out all other fields):
Sink #0
    Name: alsa_output.pci-0000_00_1b.0.analog-stereo
Source #0
    Name: alsa_output.pci-0000_00_1b.0.analog-stereo.monitor
Source #1
    Name: alsa_input.pci-0000_00_1b.0.analog-stereo

I guess one don't "just connect" to the mobile without some extra preparation. The connection connects, and after a second disconnects. I guess I need to make the computer to advertise itself as a headset, otherwise the phone might think it is something different and it doesn't want to deal with it.
This is my /etc/bluetooth/audio.conf. By manipulating its contents I never saw any effect (and of course I did reboot after each change), so maybe this file is depreciated. Or the effects are too subtle for me to see.
[General]
AutoConnect=true
Enable = Sink,Source,Gateway

[Headset]
HFP=true
MaxConnected=1
FastConnectable=false

[A2DP]
SBCSources=1
MPEG12Sources=0


text:
Q: Phase shift of voltage across capacitor in series RC Here's a simple RC circuit from an AC analysis book:

simulate this circuit – Schematic created using CircuitLab
I'm trying to determine the phase shift produced by C1 relative to that of V1 given only frequency and impedance. In the book it says that the answer is -25 degrees. Does the negative sign mean that the current lags the source voltage, contrary to the fact that capacitances cause a leading phase shift?
EDIT: Or, does the negative sign signify that it's referring to the actual phase shift minus 90 degrees? Using the tangent relationship between the capacitive reactance and resistance, I keep getting 65 degrees for an answer.

A:
In the book it says that the answer is -25 degrees

It means that the output sinewave voltage lags the input sinewave voltage by 25 degrees.
Phase lag = \$Tan^{-1}(\dfrac{R}{X_C})\$

Using the tangent relationship between the capacitive reactance and
  resistance, I keep getting 65 degrees for an answer.

It sounds like you might be taking the arctan of Xc/R (67.08 degrees).

A: One way to interpret is the one which you have stated that the waveform is leading. The other way is the one which your calculator is not allowing you to understand, usually in some calculators this issue occurs that if the phase angle goes more than 180 degrees, they just convert it into a negative number. If you add 180+25 degrees to the current phase angle you will see what the actual phase angle is which would be 205 degrees and then you will get what you expect, that is a lagging voltage across the capacitor.
Now... why add 180+(magnitude of the number)? In my calculus class when complex numbers were being taught we used to draw the real and imaginary axis, taking the imaginary part to be negative and real part to be positive that is the vector (in the circuits case which is a phasor) lies in the third quadrant, now if something lies in the third quadrant you can be sure that the angle will be greater than 180 degrees, what the calculator does is it takes the angle from the negative x-axis rather than the positive one and since it does that and is still going counter clockwise, we get the negative sign, so we add 180 to get the angle from the positive x or real axis, which is usually from where it is measured
.
Speaking in terms of circuits what happens is, getting -25 degrees does not mean that the voltage has started to lead the entire input, it means that it lags it by 205 degrees, but 205 degrees is such a big lagging (usually anything above 180 degrees is) that we just say that it sort of looks like it is leading, which is actually what is done when we see something having a phase shift of greater than 180 degrees because the waveforms just give a better feel the other way around ie leading instead of lagging because the waveform of the output looks to be coming before the input one.
.
Real sorry for not being able to give you the graphical interpretations at the moment which would have given a clearer picture of what is above but if you plot the waveform of the circuit, you will see that the phase difference between the output and input, that is
output_angle - input_angle
will be positive if you start from the angle of the input waveform , and will be negative if you start from the angle of the output waveform of the angle


text:
Q: Who owns the internet cables? When I was in United States, one thing always puzzled me.
When we took comcast internet connection, comcast guys came over to our place, setup router etc, but they never had to lay any cables.
This made to think that unlike in India, in US houses are perhaps "planned" in the sense that telephone wires go underground or inside wall etc, basically invisible and comcast people just connect the routers with these ports on wall.
But this arose some more questions. who ownes these underneath running telephone wires? are they owned by government telephone companies and what if I took internet thru telephone by 2 different companies say comcast and verizon, how would it work? How will both companies use the same telephonic wires? In such case, do they lay separate cables?

A: Telephone and cable lines go from the local office to a place in the building called the demarcation point. All that belongs to the company. From the demarcation point to the various outlets in the building is the problem of the property owner. Both cable Internet and DSL use the lines from the building to the local office.
Comcast uses the coaxial cable that your television service comes through, not the copper loop used by telephone service.

A: Generally, most broadband up to now has been able to use the copper wires that were laid by the phone company - and probably still owned by your phone company, but this can vary state to stae. The bits you don't see are are how the connections at the other end of that wire are set up.
There is enough bandwidth on these wires over short distances that you can share multiple services over them, but your bandwidth decreases the furtehr from your exchange you are.


text:
Q: Vue.js reuse form validation rules I feel that I'm duplicating a lot of code with my forms.
Every form component has this structure:
template
            <v-col cols="12" sm="6" md="4">
                <v-text-field
                        name="name"
                        v-model="user.name"
                        :rules='nameRules'
                        :label="$t('fields.name')"
                        color="elegant"
                        :error="!!errors.name"
                        :error-messages="errors.name ? errors.name : null"
                ></v-text-field>
            </v-col>
            <v-col cols="12" sm="6" md="4">
                <v-text-field
                        name="surname1"
                        v-model="user.surname1"
                        :rules='surname1Rules'
                        :label="$t('fields.surname1')"
                        color="elegant"
                        :error="!!errors.surname1"
                        :error-messages="errors.surname1 ? errors.surname1 : null"
                ></v-text-field>
            </v-col>
            <v-col cols="12" sm="6" md="4">
                <v-text-field
                        name="surname2"
                        v-model="user.surname2"
                        :rules='surname2Rules'
                        :label="$t('fields.surname2')"
                        color="elegant"
                        :error="!!errors.surname2"
                        :error-messages="errors.surname2 ? errors.surname2 : null"
                ></v-text-field>
            </v-col>
            <v-col cols="12" sm="6" md="4">
                <v-text-field
                        name="email"
                        v-model="user.email"
                        :rules='emailRules'
                        :label="$t('fields.email')"
                        color="elegant"
                        :error="!!errors.email"
                        :error-messages="errors.email ? errors.email : null"
                ></v-text-field>
            </v-col>

script
    data() {
        return {
            nameRules: [
                v => !!v || this.$i18n.translate('validation.required', {'attribute': ''}),
                v => (v && v.length <= 100) || this.$i18n.translate('validation.lt.string', {
                    'attribute': '',
                    'value': 100
                }),
            ],
            surname1Rules: [
                v => !!v || this.$i18n.translate('validation.required', {'attribute': ''}),
                v => (v && v.length <= 100) || this.$i18n.translate('validation.lt.string', {
                    'attribute': '',
                    'value': 100
                }),
            ],
            surname2Rules: [
                v => (!v || v.length <= 100) || this.$i18n.translate('validation.lt.string', {
                    'attribute': '',
                    'value': 100
                }),
            ],
            emailRules: [
                v => !!v || this.$i18n.translate('validation.required', {'attribute': ''}),
                v => (v && v.length <= 100) || this.$i18n.translate('validation.lt.string', {
                    'attribute': '',
                    'value': 100
                }),
                v => /.+@.+\..+/.test(v) || this.$i18n.translate('validation.email', {'attribute': ''}),
            ],

I'm okay with the template, I have no choice but to write all the fields I need.
But on the script, the rules are being duplicated on other components.
For example the email field, it will always have the same rules: (required, max:100, must be an email).
So it can be a way to define all the rules separately and use them on specific components? Like importing?

A: You could use Mixins.

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be "mixed" into the component's own options.

src/mixins/validationRules.js
export const validationRules = {
    data() {
        return {
            validationRules_name: [
                v => !!v || this.$i18n.translate('validation.required', {'attribute': ''}),
                v => (v && v.length <= 100) || this.$i18n.translate('validation.lt.string', {
                        'attribute': '',
                        'value': 100
                })
            ],
            //...
        }
    }
}

Add the mixin to your form components:
<template>
    <v-text-field
        :rules="validationRules_name"
    />
</template>

<script>
import { validationRules } from '@/mixins/validationRules'
export default {
    mixins: [validationRules],
    //...
}
</script>


text:
Q: Started a branch too late, change the parent of my branch I have the following situation:
A---B---F---G---H (master)
     \
      \
       C---D---E (experimental)

My problem is that B is a very-very bad thing that shouldn't have happened on master. It belongs on experimental. However F---G---H are okay. Is there a way to make everything look like this:
A---F'---G'---H' (master)
\
 \
  B---C---D---E (experiment)

I've read about rebase and stuff like that but the biggest problem is that master has been pushed to origin.

A: On master, run:
git revert B
You can then push safely, if the changes downstream of that commit are not impacted by it directly (i.e. it the contents of the commit B can be removed without upsetting the other changes that came after it. It certainly sounds like this is the case.)
This would create:
A---B---F---G---H---I (master)
     \
      \
       C---D---E (experimental)

Where I is the revert commit. Master keeps its history whilst removing the contents of B, experimental retains B's changes.
You may have to revert commit I if you later merge experimental into master.

A: git rebase --onto A B master will do.
Seems you have master already pushed to orgin, if you are certain that it is safe to overwrite master branch of the origin, just do a git push -f on master branch. Be aware that it may cause other developers have a conflict when they pull from origin.
Generally, branch in public repo should stay untouched, which means you can not expect removing commit B from the master, all you can do is fixing the mistake introduced by commit B in a new commit and push it to master again.
If it is possiable to inform your team members about the rebase and you insist to do so, then it is okay for a rewrite, just make sure this won't happer too often.


text:
Q: Mutual Inductance and the Dot Convention Can anyone please explain me, the dot convention in coil systems (Mutual and self inductance) with some related images to understand..?

A: I think you'll find this article (with pictures) helpful for dot convention and this one for mutual inductance.  Let me know if this doesn't clear it up.


text:
Q: Typescript two object union - problem with making typescript think it's the other type I encountered a really weird problem and I'm not sure if the problem is related to badly written types or it's a weird typescript thing.
So I have this props type:
type SelectAnswersProps = (
  | {
      onChange: Dispatch<SetStateAction<MultiSelectAnswerOptionsType | null>>;
      value: MultiSelectAnswerOptionsType;
      isMultiSelect: true;
    }
  | {
      onChange: Dispatch<SetStateAction<SelectAnswerOptionsType | null>>;
      value: SelectAnswerOptionsType;
      isMultiSelect: false;
    }
) & {
  displayMode?: SelectAnswerOptionsType['displayMode'];
  disabled?: boolean;
};

And then I'm trying to force typescript to read what type is being passed to onChange method.
if (isMultiSelect) {
      onChange({
        answers,
        isHeadless,
      });
    } else {
      onChange({
        answers,
        displayMode,
      });
    }

So the first onChange is correct as it shows its type as onChange: (value: SetStateAction<MultiSelectAnswerOptionsType>) => void but the second one I'd expect to be like in the types specified in props with isMultiSelect being false but instead type of 2nd onChange is as follows:
onChange: (value: SetStateAction<MultiSelectAnswerOptionsType> & SetStateAction<SelectAnswerOptionsType>) => void so kinda mix of both even though from props types you would say it's either one or another.
I reckon I've done something silly here.
Really appreciate all your help.
Thanks

A: You have defined the props to be (simplified for readability):
props: { onChange: MultiSelectDispatcher, ... } | { onChange: SelectDispatcher, ... }

That means, the props can only be the one or the other, and
Typescript doesn't know which one it is, and infers that from the usage:
if( isMultiSelect ){
  onChange({ answers, isHeadless }); // <-- TS thinks: probably the "MultiSelect" one
} else {
  onChange({ answers, displayMode });  // <-- TS already decided "MultiSelect" earlier
}

So Typescript decides which type the whole props object probably is at some point, and sticks to that decision from there on.
Use a type guard (maybe)
As a solution you might be able to use type guards (maybe not this easy, see the "But ..." below), like:
const guardMultiSelectProps = ( theProps: unknown ): theProps is MultiSelectProps => {
    return theProps.isMultiSelect;
}

if( guardMultiSelectProps( theProps ) ){
  onChange({ answers, isHeadless }); // <-- TS thiks: probably the "MultiSelect" one
} else {
  onChange({ answers, displayMode });  // <-- TS already decided "MultiSelect" earlier
}

But also Typescript might have inferred the type of the props even earlier,
or will "suddenly" do that if you make some changes to your code later.
Define the type of onChange (if possible)
I suggest, if possible, not to define two alternatives for the props object, but instead define only one type for the props, with two alternative onChange handlers.
(The React props should stay consistent anyway)
E.g:
props: {
    onChange: MultiSelectDispatcher | SelectDispatcher,
    ...
}

And also use a type guard, like:
// Note: This type guard works, but is not inherently type safe.
const guardMultiSelectOnChange = ( onChange: unknown, multiSelect: boolean ): onChange is MultiSelectDispatcher => {
    return multiSelect;
}

if( guardMultiSelectOnChange( onChange, isMultiSelect )) {
    onChange({ answers, isHeadless });
} else {
    onChange({ answers, displayMode });
}

Still problems ...
My last type guard guardMultiSelectOnChange makes another problem obvious:
We always assumed that the onChange function is the correct one if isMultiSelect is one or the other.
But nothing prevents someone to pass isMultiSelect: false and the MultiSelectDispatcher.
It would be better to type guard the function signature itself, instead of just stating onChange is MultiSelectDispatcher if
some other property (isMultiSelect) has some value.
But that will be a somewhat larger refactoring, outside the scope of this question, I guess.


text:
Q: (Mac OS X) How can I adjust the default popup size of Quick Look in Finder? If I have an item selected in Finder, I can do a Quick Look by pressing space. Is there a way to control the default size of the Quick Look popup?
Most of the time the default size is way to small for reading the content of a pdf or doc. I need a way to read the content and also be able to move to different documents (with the arrow keys). You can change the popup size but it would be forgotten the next time you do Quick Look (although Mac OS sort of remembers the location if you had moved it).
command-option-Y gives you the fullscreen version of it but I don't want it because in fullscreen mode the arrow key scrolls up and down the document instead of selecting different documents.
Thanks!

A: From Ars Technica Forum, courtesy of username DarylF2:
link to Ars Technica Forum

I figured it out, and is was actually pretty simple.
Show the package contents for "/Library/QuickLook/iWork.qlgenerator/" and edit "/Library/QuickLook/iWork.qlgenerator/Contents/Info.plist".
Change the "QLPreviewHeight" parameter value from "600" to your new value (I used "1000") and change the "QLPreviewWidth" parameter value from "800" to your new value (I used"1333").
That's it.
I didn't need to reboot or even log out and log back in for this to take effect, but I did need to open a few Pages document Quick Look previews before it seem to "take".
As always, back up the original file first and realize you are editing a file Apple didn't intend for the end user to edit.

I just tested it and it works for iWork documents only. PDF and other types of previews aren't affected. I'll try to see if there is more to it than that.

A: Not exactly an answer to your question about default size, but I had a similar problem and therefore found this discussion here.
I often found myself dragging, resizing and rearranging windows by hand with the mouse and I found this very disturbing for my workflow where I try to avoid the mouse if I can and do most things with keyboard commands (Quicksilver, etc.).
So I finally found **Optimal Layout http://most-advantageous.com/optimal-layout/ which provides many keyboard commands for moving and resizing windows (and even sending them to the second display) and it also lets you resize a quick look window to full/half/quarter screen size with 1 keystroke.
Its not changing the default size of QuickLook previews, but at least it lets you change their size quickly if they`re not big enough.


text:
Q: Android. Layout item move to right side I have android layout with three parts (imageview, textview, imageview) and I want the last part move to right side, now its near the second element.
My code:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/menu_button_bg"
    android:orientation="horizontal"
    android:paddingLeft="13dp" >

    <ImageView
        android:id="@+id/menuItemIcon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginBottom="13dp"
        android:layout_marginRight="13dp"
        android:layout_marginTop="13dp"
        android:contentDescription="@string/menuItemDesc"
        android:gravity="center_vertical" />

    <TextView
        android:id="@+id/menuItemTitle"
        android:layout_width="wrap_content"
        android:layout_height="70dp"
        android:gravity="center_vertical"
        android:textSize="16sp" >
    </TextView>

    <ImageView
        android:id="@+id/menuItemIconRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="13dp"
        android:layout_marginRight="13dp"
        android:layout_marginTop="13dp"
        android:layout_weight="0.1"
        android:contentDescription="@string/menuItemDesc"
        android:gravity="right" />

</LinearLayout>

A: You can give the TextView the following attributes:
android:layout_width="0dp"
android:layout_weight="1"

This will make the TextView stretch to use up the space between the two ImageViews. The other alternative is to use a RelativeLayout instead of a LinearLayout, but this should work for your needs.


text:
Q: Showing KPI on windows 8 app I want to show the KPI from SQL server analysis service to a windows app.
I don't have experience with SSAS. Basically I am asking how can I show BI KPI in any external application

A: I know very little about SSAS KPIs but it seems that there are (at least) two options:

*

*KPIs are exposed directly through the ADOMD.NET provider

*They can be queried using MDX
So you just need to write an application that can issue MDX queries and/or use the ADOMD.NET provider.


text:
Q: Why No Merkle tree in Hyperledger Fabric to track the world state I note that the previous Hyperledger Fabric v0.6 employs a Merkle Bucket Tree to organize the world states. And the merkle tree root hash is included in the block header, as a part of the consensus agreement.
In a similar fashion, Ethereum/Quorum and Hyperledger Sawtooth adopt Merkle tree variants in their data model to protect the world state.
But why does Hyperledger Fabric, from v1 onwards, abandon this Merkle-based data model? What is their design rationale? Is it due to efficiency or other factors?

A: Starting from Fabric 1.0, the validity of the transaction is determined in the peers, after the block was assembled.
Peers check things like endorsement policy and Multi-Version Concurrency Control conflicts, and a transaction might be deemed invalid, which means its state updates will not be applied.
At the time of generating the block in the ordering service, the validity of the transaction is unknown yet, and the orderers have no idea about the world state (unlike the peers).


text:
Q: Can I add a document from the file cabinet at the end of a generated pdf? I am using the nlapiXMLToPDF in suitescript to generate a PDF. I have a file in the file cabinet I would like to add at the end of the generated PDF file. Is this possible to do?
    var file = nlapiXMLToPDF(xml);
    response.setContentType('PDF', 'formalQuote.pdf');
    response.write(file.getValue());

A: Yes.  To do this you need to change your XML to include another file as a separate <pdf> within a <pdfset>.
Before:
<?xml version="1.0"?><!DOCTYPE pdf PUBLIC "-//big.faceless.org//report" "report-1.1.dtd">
<pdf>
    *CODE*
</pdf>

After:
<?xml version="1.0"?><!DOCTYPE pdf PUBLIC "-//big.faceless.org//report" "report-1.1.dtd">
<pdfset>
<pdf>
    *CODE*
</pdf>
<pdf src=*link to file cabinet document*></pdf>
</pdfset>