text:
Q: How to export TF trained network to a h5 file I have a trained model saved in 3 files and some tensorflow (1.x) code lines to use it.
I need to convert the model to .h5 (keras), in order to import it in Matlab.
The model is saved in 3 files:

*

*xxx.ckpt.data-00000-of-00001

*xxx.ckpt.index

*xxx.ckpt.meta

The tensorflow code lines is like:
zzz = "a function of the previous line"
session_name = "a function of xxx"
sess = tf.Session()
saver = tf.train.Saver()
saver.restore(sess,session_name)
output=sess.run(zzz, ...)

Is it possible to export the trained network to a H5 file?
If yes, how to do it?
ADD: I've asked to a friend, and appartenly it is not possible directly because, first, I have to "translate" the network stucture in Keras. This step is too hard for my level in the domain.

A: To my knowledge currently, there is no method to use checkpoint file and covert to h5(keras) directly. Instead you can achieve this by doing little workaround as mentioned below.

*

*If you want the network architecture then you need to rewrite the code in Keras.

*If you want to convert only weights (suppose you have code for the same model), you have to create a model with random weights then read the TensorFlow .ckpt file with tf.train.NewCheckpointReader then call set_weights() method for each corresponding layer.

Sample code for the same mentioned below:
reader = tf.train.NewCheckpointReader(filename)

for key in reader.get_variable_to_shape_map():
    # not saving the following tensors
    if key == 'global_step':
        continue
    if 'AuxLogit' in key:
        continue

    # convert tensor name into the corresponding Keras layer weight name and save
    path = os.path.join(output_folder, get_filename(key))
    arr = reader.get_tensor(key)
    np.save(path, arr)

You can use the saved .npy file to output model weights in h5(keras) as below.
for layer in tqdm(model.layers):
    if layer.weights:
        weights = []
        for w in layer.weights:
            weight_name = os.path.basename(w.name).replace(':0', '')
            weight_file = layer.name + '_' + weight_name + '.npy'
            weight_arr = np.load(numpy_weight_file)

        # remove the "background class"
        if weight_file.startswith('Logits_bias'):
            weight_arr = weight_arr[1:]
        elif weight_file.startswith('Logits_kernel'):
            weight_arr = weight_arr[:, 1:]

        weights.append(weight_arr)
    layer.set_weights(weights)
model.save_weights("Keras_model.h5")


text: Q: DLE не добавляет новости Постараюсь описать проблему( Хочу например я добавить новость, написал название, описание, теги и все что нужно. Нажимаю на кнопку добавить и все.. несколько секунд думает и Соединение сброшено пишут, если я перезагружу пк например, то все будет работать опять, НО всего позволяет добавить 3-5 новости, потом снова так же! И самое интересное что это происходит на двух разных сайтах, и двух разных хостингах, так что проблема точно не в них. Я не знаю что делать уже, перерыл весь интернет, но ответа так и не нашел( Может дадите верное направление.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mouse occasionally stops responding I installed Ubuntu 11.10 on my Sony Vaio a month ago.  Since then everything was ok but recently my mouse stops responding occasionally.
What could be the problem and how would I fix it?

A: I can get the mouse working again by opening a terminal and running sudo rmmod psmouse && sudo modprobe psmouse

A: Sometimes my USB mouse get stuck too, but I realized that it occours when I accidentally hit the touchpad, activating some eternal Drag & (don't) Drop.
So here is a "quick dirty fix" that always works for me: just hit the touchpad again or the touchpad left button. Then, your USB mouse will get unstuck :)
You could wan't to disable the touchpad also, if you use the USB mouse more often.


text:
Q: Browse mapped network drives when connected over VPN I have users who constantly travel outside the office.
Internally, they have mapped network drives.
They then go outside and connect via VPN which when connected bridges and puts them on the same subnet. They can ping resources on the network over the VPN without any issue.
When they try and connect to the same network drive by name it takes a long time to connect and then says the share name cannot be found.
The particulars are as follows:

*

*Internally, everything works fine

*I am running WINS on the server to which they are trying to connect.

*This WINS server is provided in the DHCP options for VPN clients

*DNS is provided in the DHCP option for VPN clients For adapter bindings

*On Windows 7 clients network adapter properties I have ensured Remote Connections are the top priority over local connections

*If connection by IP address is used, it works,  but fails when connecting by machine name

What other steps should I try to resolve the above?

A: Are you being careful to use the same naming when troubleshooting as when connecting to the network share?  For example, are you pinging:
ping servername.domain

But connecting to a server share:
\\servername\share

If you're able to ping with a fqdn, try setting up the user's network shares the same way.  I've seen issues before where not specifying the domain name when on VPN tries to access the user's local network instead.
I'm also curious if you're getting an external IP when pinging the network resources.  I've seen VPN connections to a network that's Windows domain is also the company's website, and pinging servername.domain.com ends up getting a result from a catch-all web server instead of the internal resource.

A: The obvious stuff first: In cases where this happens, is there significant packet loss over the VPN connection? Try pinging with increased packet size:
ping -l 1200 servername.your.internal.domain

I have made bad experience with even minor (~1-10%) packet loss and lots of TCP retransmissions on the connection that carries the SMB payload (ports tcp/445 and tcp/139 on the server side).
The other one is the name resolution: First workaround would be to try a network connection using the server's IP adress instead of the name. So let someone try
net use X: \\10.0.1.200\sharename

and watch if that goes through.
If that "fixes it", watch name resolution closely. Not sure about WINS, but maybe deconfigure that and try to rely on DNS. What is the primary and secondary DNS nameserver (ipconfig /all)? check if they both provide the right IP address:
nslookup servername.your.internal.domain 10.0.1.1
nslookup servername.your.internal.domain 10.0.1.2

(10.0.1.1 and 10.0.1.2 would be the DNS servers)
Maybe Windows tries a connection over IPv6 and that is silently dropped? Try to temporarily disable the IPv6-protocol on the active adapters.
Good luck!

A: A quick and dirty way to fix this would be to use the hosts.ini file.
Location:
\Windows\system32\drivers\etc\
Make sure you edit as an administrator on the machine.
Start at the bottom and add the servers they need to connect to. Type in the PRIVATE IP address, hit tab, then type in the Fully Qualified Domain Name (FQDN) Then save.
The user should now be able to connect to the server using the name.
If you would rather not use the Hosts.ini file, then check into how the remote machine is handling DNS. More than likely this is where the issue is.


text:
Q: 13" macbook pro mid 2010 no backlight I have a macbook that recently had a magnet missing inside the screen assembly, so it wasn't going to sleep. However, everything else worked fine - until, of course, I put the new magnet in and put everything back together. No backlight.
First things first: checked external monitor. Good.
Next: happened to have the body of another 13" macbook lying around sans screen assembly, so i hooked this one's assembly up to it... and whaddya know, its working fine, backlight and all!
So, I know this: a) video card/circuit works. b) display assembly, including lvds cable, works.
The display cable connector on the motherboard looks fine and I don't see any glaringly obvious blown components anywhere near it. I did go into the OS and try to increase the brightness through the system preferences, but the slider accomplished nothing. Also, the brightness keys on the keyboard do nothing as well.
I feel like I can't even know if its a software or hardware issue unless I have some specialty tools from apple themselves, although it did only happen after I messed with the hardware a bit, so that might be a clue. If anyone can help me figure this one out, has had a similar issue of sorts, or just happens to know what components are involved between the suspect areas, its really appreciated. Thanks.
P.S. Resetting SMC and PRAM (as per the official apple technician's guide) do nothing.


text:
Q: Maximum execution time of 20 seconds exceeded I am getting this error during google  auth redirect,Any idea how to resolve this issue here  is image show error when tried to sign in with google account using`

A: Its a php server configuration issue. You would have to extend the max execution time of your server. Also, try to figure out what script you are running that takes so long. Normally, one script shouldn't run that long without responding to the user.
Try creating a job for the task or running it as a command.
Change Max Execution Time
Laravel Jobs
Commands


text:
Q: Excercise from Isaacs' book "Character theory of Finite Groups" I am trying to prove a statement from Isaacs' book "Character theory of Finite Groups" (exercise $8.5$).

Let $\chi \in \operatorname{Irr}(G)$ and suppose $|G| = mn$, with $(m, n) = 1$. Assume that $\chi(x) = 0$ for all $1 \neq x \in G$ such that $x^{n} = 1$. Suppose $y \in G$ and $y^{m} \neq 1$. Show that $\chi(y) = 0$.

I tried to solve this problem like this:
Since $y^m\neq 1$, we can say that there is at least one prime divisor of $n$ that is a divisor of $|y|$.
$[\chi, \chi] = \frac{1}{|G|}\sum\limits_{x \in G}\chi(x)\overline{\chi(x)} = \frac{1}{|G|}\sum |\chi(x)|^{2} = 1$
In the second equality, the sum is taken over those $x\in G : |x|\not\mid \; n$.
Let 's try to use the following theorem:

Let $\chi \in \operatorname{Irr}(G).$ Let $\exists \; p \in \mathbb{P}$ such that $p$ doesn't divide $\frac{|G|}{\chi(1)}$. Then $\chi(g) = 0$ for all $g \in G$ such that $p \; | \; |g|$.

If $n \; |\; |y|$, then our statement will be fulfilled.
If $\exists \; p \in \mathbb{P}$ such that $p$ doesn't divide $\frac{|G|}{\chi(1)}$ and $p \; | \; |y|$, then our statement will be fulfilled.
If $\chi(1) = |G|$, then our statement will be fulfilled
Unfortunately, I'm stuck in this place, and I don't know what to do next to solve this problem.
I will be grateful for any help!


text:
Q: Adding Bootstrap Glyphicon in Slim/Ruby on Rails form as a placeholder As of right now, the code for the relevant section:
= form_for(resource, as: resource_name, url: registration_path(resource_name), html:{id:'registration-form'}) do |f|
    = devise_error_messages!

    div style="padding:4px"
            = f.email_field :email, autofocus: true, placeholder: "Email address", class:"form-control", style:"height:60px"

And the output is looking like this, which I think is pretty okay:

(source: trillian.im)
But I'd like to get the Bootstrap 3 envelope Glyphicon in front of the text.  I'm brand new to Rails as of this week, and haven't been able to find help for this idea elsewhere.  It looks like this post is very close to what I want to do, but I'm not sure how to do that against the f.email_field tag. Thanks to anyone with advice!

A: The HTML placeholder attribute only accepts plain text.  You can't put any tags in there, which is what you would need in order to do what you want.
You can try putting the icon behind or beside your text field so that it appears to be a place holder instead.


text:
Q: How can I compare two linked columns from one table with other two linked columns in another table? I need some help on getting the proper formula for validating the following.
We have Customer list with Customer name, Customer number registered in our system, Customer number in another billing system. As we have found some discrepancies in data we need to validate now one old list with the same data with the last updated data in our system.
Meaning we need to compare CU Number+Cu Billing Number column from 1st list with the same two columns from the second list, as we have found out that there are discrepancies and mixtures of CU number and not correct CU billing number next to them:
List 1:
CU name     CU number    CU billing number
Aert        BR345        3456
Bert        BR456        2345
Port        BR567        5678

List 2:
CU name     CU number    CU billing number
Aert        BR345        3456
Bert        BR344        2345
Port        BR567        5678

Could you advice what formula can help me cross check the 2 columns from List 1 with the two columns from List 2?

A: First of all, please note CharlieRB's comment, there are not enough details in your question so I am basing my answer on some assumptions.  Secondly, this is a very elementary approach to validating your data but it'll do the job relatively quickly.
Assuming your sample table's columns are A, B, and C respectively, and row 1 is used for those headers; add headers "B Column Validation" to E1 and "C Column Validation" to F1 (See image below).
Now using the same layout, paste the back-up data in a separate sheet of the same workbook.
Go back to the original sheet and enter this formula in E2:
=IF($B2=Sheet2!$B2, "Good", "Bad")

Then this formula in F2:
=IF($C2=Sheet2!$C2, "Good", "Bad")

Note: Obviously if your sheet is named differently or your starting cells are in different locations, you'll need to modify your formula to reflect it.
Drag fill both columns down to the final row of your spreadsheet.  Finally, if you want to color-code it you can use conditional formatting.

Again, this is a VERY elementary way of doing this and there may be better solutions but this will work if all that you're doing is comparing two columns of data against each other.

A: This does it
Sub EeekPriates()

Dim row As Integer
row = 2

Dim cols(2) As String
cols(0) = "A"
cols(1) = "B"
cols(2) = "C"

Dim i As Integer
For i = 0 To UBound(cols)

Dim col As String
col = cols(i)

Do While (Worksheets("Sheet1").Range(col & row).Value <> "")

    Dim ws1value As String
    Dim ws2value As String

    ws1value = Worksheets("Sheet1").Range(col & row).Value
    ws2value = Worksheets("Sheet2").Range(col & row).Value

    If (ws1value <> ws2value) Then
        Worksheets("Sheet1").Range(col & row).Interior.ColorIndex = 3
    End If

row = row + 1
Loop
row = 2
Next i

End Sub

I copied my data into 2 worksheets
So, Sheet1

Sheet2

After the macro runs, sheet2 remains the same as the screenshot above, this is what Sheet1 looks like


text:
Q: Why is No manual entry for pthread_mutex_lockerror prompted? I want to check the use of the pthread_mutex_lock function, so I execute the command  man pthread_mutex_lock, the result appears No manual entry for pthread_mutex_lock.
I checked the information on the Internet and said that there was a No manual entry for pthread_mutex_lock prompt, need to install manpages-posix-dev.
So I'm ready to install manpages-posix-dev(I execute the command: apt-get install manpages-posix-dev), but E: Unable to locate package manpages-posix-dev prompts me again. Why?I'm using the debian 10 system.
gyz@debian:~$ man  pthread_mutex_lock
No manual entry for pthread_mutex_lock
gyz@debian:~$ sudo apt-get install manpages-posix-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package manpages-posix-dev
gyz@debian:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 10 (buster)
Release:        10
Codename:       buster
gyz@debian:~$ getconf LONG_BIT
64
gyz@debian:~$ cat /proc/version
Linux version 4.19.0-9-amd64 (debian-kernel@lists.debian.org) (gcc version 8.3.0 (Debian 8.3.0-6)) #1
SMP Debian 4.19.118-2+deb10u1 (2020-06-07)

A: sudo apt-get install glibc-doc.


text:
Q: Is there a way to tell which EventLog caused the EntryWritten event in C#? I'm working on a web application that shows event logs data, similar to Event Viewer. The application also has to provide a way for users to subscribe to event logs and receive notifications when an entry is written to subscribed logs, using a web service.
I'm using this code to subscribe to an event log in the web service:
EventLog eventLog = new EventLog(observer.logName, observer.machineName);
eventLog.EnableRaisingEvents = true;
eventLog.EntryWritten += new EntryWrittenEventHandler(eventLog_EntryWritten);
eventList.Add(eventLog);

I'm trying to use observers as subscribers to event logs, and when an EventWritten event is handled, call the Update method of one observer. The problem is, I don't know how to differentiate event logs, since they all use the same event handler. I'm doing this because the number of event logs differs from one machine to another. Also, I want observers to handle only one type of EventLog, ie. one observer would send an e-mail when an event is written to the Application log.
I use this line of code to get all logs on the current computer:
remoteEventLogs = EventLog.GetEventLogs(machineName);

EventWritten event handler has this object sender parameter, but Visual Studio shows its type as EventLogInternal, which I can't use, and I can't cast the sender to EventLog to get EventLog.Log property. If I try to cast it, like this:
void eventLog_EntryWritten(object sender, EntryWrittenEventArgs e)
    {
        var log = (EventLog)sender;
    }

I get an exception saying I can't cast an EventLogInternal to EventLog.
Is there a way to know which EventLog fires the event?
Thanks

A: I think the problem is, that the whole concept of the EventLog class is that it assumes it works upon a single Log - which it does. So neither the EventWrittenEventArgs nor the EventEntry class sport a member that contains the Log-name, as it is implicitly given by the associated EventLog-instance. Bad is of course, that you cannot get to it inside the EventWritten-handler.
You could create a wrapper around System.Diagnostics.EventLog, like so:
class MyEventLog : EventLog
{
    public MyEventLog(string logName, string machineName)
        : base(logName, machineName)
    {
        base.EnableRaisingEvents = true;
        base.EntryWritten += MyEventLog_EntryWritten;
    }

    void MyEventLog_EntryWritten(object sender, EntryWrittenEventArgs e)
    {
        Console.WriteLine("Entry in {0} log.", base.Log);

        // Your code
    }
}

Then use MyEventLogin places where you normally would use EventLog. Probably give it a better name though.
You could also factor out the "Your Code" part by providing an Action<string, EntryWrittenEventArgs> property that is being called from inside MyEventLog_EntryWritten and can be set to your "external" handler function.

A: Another option would be to use reflection along these lines:
string log = (string)sender.GetType().GetProperty("Log").GetValue(sender, null);

since sender in this case actually has the Log property.

A: I think that what you are looking for can be found in the EntryWrittenEventArgs.
The MSDN shows there is a property called Entry that shows you all kinds of information about what just got logged. There are some properties that might help you in the EventLogEntry class, such as MachineName or UserName.
Here is a link to the Args class
http://msdn.microsoft.com/en-us/library/system.diagnostics.entrywritteneventargs.aspx
Here is a link to the Entry class
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogentry.aspx
I don't see a direct link to the specific event log, but if you poke around in that class with the debugger the Entry object might give you enough information to look it up.
I hope this helps some.

A: I agree with the idea of wrapping the EventLog class within another class as suggested by Christian. I recently worked on such a requirement.
This is the class that I created
 public class EventLogWatcher : EventLog
{
    Action<string, EntryWrittenEventArgs> _changeHandler;
    public EventLogWatcher(string logName, Action<string, EntryWrittenEventArgs> changeHandler)
        : base(logName)
    {
        _changeHandler = changeHandler;
    }

    public void EnableCapture()
    {
        base.EnableRaisingEvents = true;
        base.EntryWritten += EventLogChangeHandler;
    }

    public void DisableCapture()
    {
        base.EnableRaisingEvents = false;
        base.EntryWritten -= EventLogChangeHandler;
    }

    private void EventLogChangeHandler(object sender, EntryWrittenEventArgs e)
    {
        _changeHandler(base.Log, e);
    }
}

Here is a usage
 foreach (string eventlogType in LogTypes)
            logWatchers.Add(new EventLogWatcher(eventlogType, EventLogChangeHandler));

        foreach (EventLogWatcher localLog in logWatchers)
        {
            try
            {
                localLog.EnableCapture();
            }
            catch(Exception ex)
            {
                EventManager.PublishExceptionLogMessage(ex);
            }
        }
        EventManager.PublishInfoLogMessage($"Started EventLog listeners for {string.Join(",", LogTypes)} logs");

 private void EventLogChangeHandler(string eventLogType, EntryWrittenEventArgs e)
    {
        try
        {
            if (UploadAllowed(eventLogType, e))
            {

                Dm.EventLog model = _eventLogEntryMapper.MapEntryToModel(e);
                Task.Factory.StartNew(
                       () => _eventLogUploadService.UploadEventLog(model),
                       _cancellationTokenProvider.Token,
                       TaskCreationOptions.None,
                       TaskScheduler.Default);
            }
        }
        catch(Exception ex)
        {
            EventManager.PublishExceptionLogMessage(ex);
        }

    }

A: Another option would be to change the event-registration like this:
eventLog.EntryWritten += (sender, e) => eventLog_EntryWritten(eventLog, e);


text:
Q: Adding secondary constructor to parent unexpectedly affects child classes I have a (seemingly) odd problem. It can be reproduced with just a few lines:
open class Parent(val map: HashMap<String, Any>) {
    // constructor(unusedArgument: Int): this(hashMapOf())
}

class Child: Parent(hashMapOf(Pair("key", "value")))

It compiles and works as expected as long as I keep Parent's secondary constructor commented out.
Once I put it back in, this lint error pops up where the Child's parent constuctor is called:

Error: None of the following functions can be called with the
  arguments supplied:
public constructor Parent(map: HashMap) defined in Parent
public constructor Parent(unusedArgument: Int) defined in Parent

The error goes away if any of these is true:

*

*I specify variance as HashMap<String, out Any>,

*My secondary constructor is empty,

*map is declared as Map instead of HashMap (which I don't do because for my purposes I need it to implement Serializable).

To be honest, it doesn't make much sense to me. Why does it happen only if I add non-empty secondary constructor to the parent class? What does it have to do with anything? And how exactly do these "fixes" fix it?
Thanks.

A: This may be by design or a compiler bug. I recommend reporting it at Kotlin (KT) | YouTrack.
As a workaround, you can explicitly declare the generic types used in the HashMap when calling the Parent constructor:
class Child : Parent(hashMapOf<String, Any>(Pair("key", "value")))

I'm not certain why  the compiler accepts HashMap<String, String> as HashMap<String, Any> when the secondary constructor isn't defined but doesn't accept it when the secondary constructor is defined but sometimes the compiler simply fails to infer generic types and you need to explicitly declare them.


text:
Q: How can we add the master record type in the pick list of record type, After creating different record types for account? When we made different record types of an object, how can we add master record type in pick list also?
In pick list option, all custom record type other than master record type are shown.


text:
Q: Is there a way to crossfade relatively positioned divs (with dynamic heights)? What I'm trying to do is fade div 1 out and fade div 2 in at the same time, over each other...
Both divs are relative and are vertically stacked - the content within those divs is also likely to change constantly so fixed margins, heights, etc. won't work...
Here's a fiddle: https://jsfiddle.net/jwzwycdm/
I've added height: 0 but it completely kills the fade animations:
   div { height: 0px;
         opacity: 0;
         transition: opacity 0.5s; }

  .active { height: 100%;
            opacity: 1;
            transition: opacity 0.5s; }

This is the exact effect I'm trying to achieve - using absolute positioning does the trick but completely ruins any elements that may come below those two:
https://jsfiddle.net/jwzwycdm/3/

A: You need to nest the 2 DIVs in a parent DIV with position:relative. Then make the two child DIVs position:absolute. See code:
https://jsfiddle.net/jwzwycdm/5/


text:
Q: Is there a way to remove attributes from an inherited property? Is it possible to remove attributes from inherited properties?  I thought that by using the new keyword I could do so...
 public class Person
 {
     [Required]
     public string FirstName { get; set; }

     [Required]
     public string LastName { get; set; }
 }

 public class Employee : Person
 {
     [Required]
     public string JobTitle { get; set; }

     public new string FirstName { get; set; }
 }

... but this doesnt work at all.  This surprises me because the new is specifically there to hide inherited members.

A: Your Employee class now has 2 FirstName properties, one of them is still  [Required] ...
Direct answer: No, you cannot remove attributes for as far as I know. That would violate the substitution principle. When an Employee IS-A Person then the properties of Person.FirstName apply.
And: the new keyword here only serves to suppress the 'X is hiding base class member..' warning. It has no effect whatsoever on the semantics of your code.


text:
Q: Check whether sentence contains certain words I have a sentence like:
I`ve got a Pc

And a set of words:
Hello
world
Pc
dog

How can I check whether the sentence contains any of those words? In this example I would have a match with Pc.
Here is what I got so far:
public class SentenceWordExample {
    public static void main(String[] args) {
        String sentence = "I`ve got a Pc";
        String[] words = { "Hello", "world", "Pc", "dog" };

       // I know this does not work, but how to continue from here?
       if (line.contains(words) {
            System.out.println("Match!");
       } else {
            System.out.println("No match!");
        }
    }
}

A: I'd stream the array, and then check if the string contains any of its elements:
if (Arrays.stream(stringArray).anyMatch(s -> line.contains(s)) {
    // Do something...

A: I prefer using a regex approach here, with an alternation:
String line = "I`ve got a Pc";
String[] array = new String[2];
array[0] = "Example sentence";
array[1] = "Pc";
List<String> terms = Arrays.asList(array).stream()
    .map(x -> Pattern.quote(x)).collect(Collectors.toList());
String regex = ".*\\b(?:" + String.join("|", terms) + ")\\b.*";
if (line.matches(regex)) {
    System.out.println("MATCH");
}

The exact regex which the above snippet generates is:
.*\b(?:Example sentence|Pc)\b.*

That is, we form an alternation containing all keyword terms for which we want to search in the input string.  Then, we use that regex with String#matches.


text:
Q: Some auto-generated controls missing My app today started throwing the following error:
The name 'Control' does not exist in the current context

It's happening only in 2 controls in the page, even if I rename them. If I add the control declaration myself in the .designer.cs file it works but when rebuilt it throws the error again.
Any ideas what might be wrong? I can paste all the code but I feel there's just too much to paste, but if you want me to post some of the code just tell me.

A: The designer file for an aspx sometimes does no correctly write code for controls. so in such a case delete the designer file then right click on you .aspx file and Click "Convert to Web Application" this action regenerates the designer file again correctly

A: You should check the code behind the filename and inherits property on @Page directive and ensure that they both match....
You should also be sure to exclude other page which is referncing to same code behind file...


text:
Q: Filler at the end of a struct for future growth This document called "Good Practices in Library Design, Implementation, and Maintenance" by Ulrich Drepper says (bottom of page 5):

[...] the type definition should always create at least a minimal
  amount of padding to allow future growth
[...]
Second, a structure should contain at the end a certain number of fill bytes.
struct the_struct
{
  int foo;
  // ...and more fields
  uintptr_t filler[8];
};

[...]
If at a later time a field has to be added to the structure the type definition can be changed to this:
struct the_struct
{
  int foo;
  // ...and more fields
  union
  {
    some_type_t new_field;
    uintptr_t filler[8];
  } u;
};

I don't see the point of adding this filler at the end of the structure. Yes it means that when adding a new field (new_field) to the structure, it doesn't actually grow. But isn't the whole point of adding new fields to a structure that you didn't knew you were going to need them? In this example, what if you want to add not one field but 20? Should you then use a filler of 1k bytes just in case? Also, why does is it important that the size of a struct doesn't change in subsequent versions of a library? If the library provides clean abstractions, that shouldn't matter right? Finally, using a 64 bytes filler (8 uintpr_t (yes, it's not necessarily 64 bytes)) sounds like a waste of memory...
The document doesn't go into the details of this at all. Would you have any explanations to why this advice "adding fillers at the end of struct to plan for future growth" is a good one?

A: Depending on circumstances, yes, the size of the structure can be important for binary compatibility.
Consider stat().  It's typically called like this:
struct stat stbuf;
int r = stat(filename, &stbuf);

With this setup, if the size of the stat structure ever changes, every caller becomes invalid, and will need to be recompiled.  If both the called and the calling code are part of the same project, that may not be a problem.  But if (as in the case of stat(), which is a system call into the Unix/Linux kernel) there are lots and lots of callers out there, it's practically impossible to force them all to recompile, so the implication is that the size of the stat structure can never be changed.
This sort of problem mainly arises when the caller allocates (or inspects/manipulates) actual instances of the structure.  If, on the other hand, the insides of the structure are only ever allocated and manipulated by library code -- if calling code deals only with pointers to the struct, and doesn't try to interpret the pointed-to structures -- it may not matter if the structure changes.
(Now, with all of that said, there are various other things that can be done to mitigate the issues if a struct has to change size.  There are libraries where the caller allocates instances of a structure, but then passes both a pointer to the structure, and the size of the structure as the caller knows it, down into the library code.  Newer library code can then detect a mismatch, and avoid setting or using newer fields which an older caller didn't allocate space for.  And I believe gcc, at least, implements special hooks so that glibc can implement multiple versions of the same structure, and multiple versions of the library functions that use them, so that the correct library function can be used corresponding to the version of the structure that a particular caller is using.  Going back to stat(), for example, under Linux there are at least two different versions of the stat structure, one which allocates 32 bits for the file size and one which allocates 64.)

A:
But isn't the whole point of adding new fields to a structure that you
  didn't knew you were going to need them?

Well yes, if you knew all along that you would need those members, then it would be counter-productive to intentionally omit them.  But sometimes you indeed discover only later that you need some additional fields.  Drepper's recommendations speak to ways to design your code -- specifically your structure definitions -- so that you can add members with the minimum possible side effects.

In this example, what if you
  want to add not one field but 20?

You don't start out saying "I'm going to want to add 20 members".  Rather, you start out saying "I may later discover a need for some more members."  That's a prudent position to take.

Should you then use a filler of 1k
  bytes just in case?

That's a judgment call.  I recon that a KB of extra space in the structure definition is probably overkill in most cases, but there might be a context where that's reasonable.

Also, why does is it important that the size of a
  struct doesn't change in subsequent versions of a library? If the
  library provides clean abstractions, that shouldn't matter right?

How important it is that the size remains constant is a subjective question, but the size is indeed relevant to binary compatibility for shared libraries.  Specifically, the question is whether I can drop a new version of the shared lib in place of the old one, and expect existing programs to work with the new one without recompilation.
Technically, if the definition of the structure changes, even without its size changing, then the new definition is incompatible with the old one as far as the C language is concerned.  In practice, however, with most C implementations, if the structure size is the same and the layout does not change except possibly within previously-unused space, then existing users will not notice the difference in many operations.
If the size does change, however, then

*

*dynamic allocation of instances of the structure will not allocate the correct amount of space.

*arrays of the structure will not be laid out correctly.

*copying from one instance to another via memcpy() will not work correctly.

*binary I/O involving instances of the structure will not transfer the correct number of bytes.

There are likely other things that could go wrong with a size change that would (again, in practice) be ok under conversion of some trailing padding into meaningful members.
Do note: one thing that might still be a problem if the structure members change without the overall size changing is passing structures to functions by value and (somewhat less so) receiving them as return values.  A library making use of this approach to provide for binary compatibility would do well to avoid providing functions that do those things.

Finally, using a 64 bytes filler (8 uintpr_t (yes, it's not
  necessarily 64 bytes)) sounds like a waste of memory...

In a situation in which those 64 bytes per structure is in fact a legitimate concern, then that might trump binary compatibility concerns.  That would be the case if you anticipate a very large number of those structures to be in use at the same time, or if you are extremely memory-constrained.  In many cases, however, the extra space is inconsequential, whereas the extra scope for binary compatibility afforded by including padding is quite valuable.

The document doesn't go into the details of this at all. Would you
  have any explanations to why this advice "adding fillers at the end of
  struct to plan for future growth" is a good one?

Like most things, the recommendation needs to be evaluated relative to your particular context.  In the foregoing, I've touched on most of the points you would want to consider in such an evaluation.


text:
Q: .dll Equivalent on Mac OS X I am from a Windows background and I am used to creating SDKs by creating (.dll)s and then distributing all the libraries and Documentation.
So, if a user wants to use it, he adds a reference to the library and uses it. However, in a Mac, I am working on a SDK and I want a way of creating and distributing Mac libraries.
(I want to create the library in Objective-C)
Please help me :)

A: If you're creating a Mac library, you have either the option of creating a dylib, which includes only the compiled binary for the library, or creating a framework, which includes the compiled binary as well as headers and other bundle resources used by the library, in a single package. Frameworks are the preferred method of library distribution for the Mac.
If you're creating an iOS library, iOS doesn't support dynamic libraries of any kind (no dylibs or frameworks) so you're stuck with creating static libraries to distribute your code.

A: Both Mac and iOS have Dynamicly Linked Libraries. They just are not called that. They are generally just referred to as Shared Libraries and they typically are wrapped in Frameworks.
Unfortunately, iOS limits the use of Shared Libraries to System Libraries and does not allow installing shared libraries on non-jailbroken devices.
Both platforms also support Static Libraries.


text:
Q: Python - Get a date dd.mm.yyyy from any string bsp.("aa;l sd20.10.1980adgf") How should I do this?
Should I use Regex? If so, how?
And in the example below I want to know if this string(tr.get_text()) contains a date in the format dd.mm.yyyy. One of its outputs could look like this ('\nMi\n11.10.201708:1509:45HS H "Ulrich Santner" (NTEG230E)Abhaltungfix')
for page in pages:
    for tr in page.find_all('tr', {'class': 'coTableR'}):
        print(tr.get_text())

A: Using Regex.
import re
s = '\nMi\n11.10.201708:1509:45HS H "Ulrich Santner" (NTEG230E)Abhaltungfix'
m = re.search(r"(?P<date>\d{2}\.\d{2}\.\d{4})", s)
if m:
    print(m.group('date'))

Output:
11.10.2017


text:
Q: Javafx 8 using KeyEvents with ImageView I am trying to make a game on Javafx 8 using NetBeans 8.1. The super class of all my game objects is ImageView and I would like to handle key events within a game object instead of in my Scene. The problem is that KeyEvents seem to only work on the Scene and when I add a KeyEvent Handler to my game object nothing happens when I press the keys. Is there anyway to add KeyEvents to any Node, such as an ImageView, and have it work? Below is an example of what I am aiming for (VisibleGameObject extends ImageView):
package hangmanElements;

import javafx.event.EventHandler;
import javafxgame2D.gameObjects.VisibleGameObject;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

public class HangmanPost extends VisibleGameObject
{
    public HangmanPost()
    {
        super(new Image("/resources/hangmanPost.png"));
        setOriginAtCenter();
        setPosition(100, 250);
        setOnKeyPressed(new EventHandler<KeyEvent>(){

        @Override
        public void handle(KeyEvent event)
        {
            if(event.getCode() == KeyCode.UP)
            {
                System.out.println("Up pressed MAN!");
            }
        }
    });
}

@Override
public void update()
{

}
}

A: Key events are only generated by scene graph nodes when they have keyboard focus. By default, an ImageView does not gain keyboard focus. You need to call
setFocusTraversable(true);

on the ImageView.


text:
Q: Does Google wait for an infinite refresh_token for cloud partner calls? I'm working today on a partner environment related to Google Home.
Concretely, when I use google home to give orders on devices, Google calls my API to execute them (as it does with Philips Hue, Netatmo etc ...).
My problem is this: I use keycloak for OAuth management. the Google console has been configured to use it and it works. However my refresh_token expire and this forces the user to delete the linked account and then postpone it.
My question is this: Does Google expect to get an infinite refresh_token after giving its authorization_code? Or I missed something, because Google does not seem to restart the normal connection procedure.
Keycloak 3.2, Google homegraph action-on-google

A: Typically, yes, Google assumes the refresh_token has either no expiration or an extremely long expiration period. But it does acknowledge that the refresh_token can either expire or be revoked. In that case, you need to make sure your OAuth server returns HTTP code 400 with the OAuth error invalid_grant.

A: I personnaly consider a good practice to revoke refresh tokens after an period of inactivity.
This gives a pretty good user experience while keeping the database updated.


text:
Q: .css jquery attribute not applying css to div tag i've created a function to get the pathname of the webpage and if it matches the id of the menu item then it will add a css property to the div tag, showing the div as current page. heres the website im testing on: http://kwp.host22.com. im using alerts to check that variables are correct. heres my html.

Home

Cleaning

Contact Us

and heres my jquery:
var path = window.location.pathname;
        if(path === "/")
            {
            var pathname = path.replace("/","index.html");
            }
        else
            {
            pathname = path.replace("/","");
            }
        alert("pathname = " + pathname);
        var id = "#" + pathname;
        alert("id = " + id);
        $('a').each(function()
            {
            var href = $(this).attr("href");
            alert("href = " + href);
            if (href === pathname)
                {
                $(id).css('box-shadow','0px 0px 20px inset');
                }

but its not applying the box shadow to the div tag.
any help would be appreciated im still learning jquery.
thanks

A: The issue is that jQuery will interpret the id "#index.html" as "an element with id index and class html".  You need to not use a dot in your id for this to work, or escape the dot.
Alternatively, you could do an attribute selector, something like:
$("[href='"+pathname+"']").find('.navblocks').css('box-shadow','0px 0px 20px inset');

Which would be a lot less work overall

A: The problem is the . within your id. You need to escape this in order for jQuery to read it as an ID and not an ID followed by a Class selector:
id = "#index\\.html"

For this you can use:
var id = "#" + pathname.replace('.', '\\\.');

If we test this within the JavaScript console on your page, we get the following result:

A: The issue appears to be with the ids that you are using such as #index.html and #cleaning.html to select the correct DOM element. This is incorrect and you should really be just using #index and #cleaning as these are valid IDs (using . in an ID is illegal HTML/XHTML).
One way of getting around this could be to split the id like this so you can then just use the html filename rather than including the file extension:
 var path = window.location.pathname;
        if(path === "/")
            {
            var pathname = path.replace("/","index.html");
            }
        else
            {
            pathname = path.replace("/","");
            }

        pathname = pathname.split(".");
        var id = "#" + pathname[0];

        alert("id = " + id);
        $('a').each(function()
            {
            var href = $(this).attr("href");
            alert("href = " + href);
            if (href === pathname)
                {
                $(id).css('box-shadow','0px 0px 20px inset');
                }

Now you will be using #index rather than #index.html as the file extension has now been removed. The code that I have added to do this is:
pathname = pathname.split(".");
var id = "#" + pathname[0];

Source: http://www.w3schools.com/jsref/jsref_split.asp


text:
Q: Doing simple Ajax call - ajax URL not outputting anything app/etc/modules/Custom_Customajax.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Custom_Customajax>
             <active>true</active>
             <codePool>local</codePool>
        </Custom_Customajax>
    </modules>
</config>

app/code/local/Custom/Customajax/controllers/AjaxController.php
<?php
class Custom_Customajax_AjaxController extends Mage_Core_Controller_Front_Action {

    public function indexAction() {
        $this->loadLayout();
        $this->renderLayout();
    }
}

app/code/local/Custom/Customajax/etc/config.xml
<?xml version="1.0"?>
<config>
  <modules>
    <Custom_Customajax>
      <version>0.1.0</version>
    </Custom_Customajax>
  </modules>
  <frontend>
    <routers>
      <Customajax>
        <use>standard</use>
        <args>
          <module>Custom_Customajax</module>
          <frontName>customajax</frontName>
        </args>
      </Customajax>
    </routers>
    <layout>
      <updates>
        <customajax>
          <file>customajax.xml</file>
        </customajax>
      </updates>
    </layout>
  </frontend>
</config>

mytemplate/layout/customajax.xml
<?xml version="1.0"?>
<layout version="1.0">
  <customajax_ajax_index>
    <block type="customajax/customajax" name="root" output="toHtml" template="customajax/customajax.phtml" />
  </customajax_ajax_index>
</layout>

mytemplate/template/customajax/customajax.phtml
<?php

echo 'test';

Ajax call
$('.submit-form').click(function(e) {
    e.preventDefault();
    $.ajax({
        url: "/mysite/customajax/ajax/index",
        type: "POST",
        success: function(data) {
            if(data.success) {
                $('#results').html(data.message);
            }
        }
    });
});

A: 1. Change your module's router configuration like this.
       <routers>
          <customajax>
            <use>standard</use>
            <args>
              <module>Custom_Customajax</module>
              <frontName>customajax</frontName>
            </args>
          </customajax>
       </routers>

Note the change that you made here is using customajax instead of Customajax. Now Magento will recognize your customajax_ajax_index layout handle.
2. Make sure your custom block exist. As per the definition in your layout XML file, Magento needs the following block class to be defined inside your module.
FILE : app\code\local\Custom/Customajax/Block/Customajax.php
<?php
class Custom_Customajax_Block_Customajax extends Mage_Core_Block_Template
{
}

Job is not over. Eventhough we defined our custom block, Magento do not know where exactly it needs to look for our custom block. So we need to tell to Magento that, "she" should look in our own module. For this add this code snippet in config.xml
<global>
    <blocks>
        <custom_customajax>
            <class>Custom_Customajax_Block</class>
        </custom_customajax>
    </blocks>
</global>

3. I am not sure about this point. You need to set url keyword like this
    url: "www.domain.com/customajax/ajax/index",

where www.domain.com is your site's base url.
You are done. Now clear the cache and then try again


text:
Q: Renaming a table where only part of the table name is known I'm working on some tools to facilitate importing a lot of data and cleaning it up before appending to another table.
As part of this procedure I need to rename an imported table before the rest of my processes.
Private Sub btnRenameTable_Click()
    DoCmd.Rename "NEW_DATA", acTable, "DATA SOURCE"
End Sub

The problem I have is the table to be renamed has a variance in the form of a number at the end i.e. DATA SOURCE 01, DATA SOURCE 02, etc.
How can I modify the above code to find the table and rename it without having to modify the original name every time?  I just need it to check for "DATA SOURCE" in the table title, the numbers are irrelevant to my needs.

A: You're looking for the Like operator to find the renamed table.  Posting an example, you can easily modify it to your use (contains example of the Like operator and using an index to rename all your new tables in one go instead of having to spam click a button)
Dim td As TableDef
Dim i as Long
i = 1
For Each td In CurrentDb.TableDefs
    If td.Name Like "NEW SOURCE*" Then
        DoCmd.Rename "NEW SOURCE", acTable, "DATA SOURCE" & Format(i,"00")
        i = i + 1
    End If
Next


text:
Q: pdfTeX is not running in PDF mode - problems with package transparent I am using to compile my MWE
\listfiles
\documentclass{article}

\usepackage{transparent}

\usepackage[ngerman]{babel}

\begin{document}

\texttransparent{0.5}{Hello World}

\end{document}

But it won't compile because of the error message Package transparent Warning: Loading aborted, because pdfTeX is not running in PDF mode..
Whole log:
This is TexpadTeX (based on TeX Version 3.14159265 with e-TeX extensions) running in extended mode embedded in Texpad 623 (preloaded format=latex 2021.3.29)  29 JUL 2021 11:44
**
(Ohne Titel.tex
LaTeX2e <2017-04-15>
Babel <3.16> and hyphenation patterns for 84 language(s) loaded.
(article.cls
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
(size10.clo
File: size10.clo 2014/09/29 v1.4h Standard LaTeX file (size option)
)
\c@part=\count79
\c@section=\count80
\c@subsection=\count81
\c@subsubsection=\count82
\c@paragraph=\count83
\c@subparagraph=\count84
\c@figure=\count85
\c@table=\count86
\abovecaptionskip=\skip41
\belowcaptionskip=\skip42
\bibindent=\dimen102
) (transparent.sty
Package: transparent 2016/05/16 v1.1 Transparency via pdfTeX's color stack (HO)
(ifpdf.sty
Package: ifpdf 2017/03/15 v3.2 Provides the ifpdf switch
)

Package transparent Warning: Loading aborted, because pdfTeX is not running in PDF mode.

) (babel.sty
Package: babel 2018/01/04 3.16 The Babel package
(switch.def
File: switch.def 2018/01/04 3.16 Babel switching mechanism
) (ngerman.ldf
Language: ngerman 2016/11/02 v2.9 German support for babel (new orthography)
(ngermanb.ldf
Language: ngermanb 2016/11/02 v2.9 German support for babel (new orthography)
(babel.def
File: babel.def 2018/01/04 3.16 Babel common definitions
(switch.def
File: switch.def 2018/01/04 3.16 Babel switching mechanism
)
\babel@savecnt=\count87
\U@D=\dimen103
(txtbabel.def)
\bbl@dirlevel=\count88
)
Package babel Info: Making " an active character on input line 125.
))) (Ohne Titel.aux)
LaTeX Font Info:    Checking defaults for OML/cmm/m/it on input line 8.
LaTeX Font Info:    ... okay on input line 8.
LaTeX Font Info:    Checking defaults for T1/cmr/m/n on input line 8.
LaTeX Font Info:    ... okay on input line 8.
LaTeX Font Info:    Checking defaults for OT1/cmr/m/n on input line 8.
LaTeX Font Info:    ... okay on input line 8.
LaTeX Font Info:    Checking defaults for OMS/cmsy/m/n on input line 8.
LaTeX Font Info:    ... okay on input line 8.
LaTeX Font Info:    Checking defaults for OMX/cmex/m/n on input line 8.
LaTeX Font Info:    ... okay on input line 8.
LaTeX Font Info:    Checking defaults for U/cmr/m/n on input line 8.
LaTeX Font Info:    ... okay on input line 8.
! Undefined control sequence.
l.10 \texttransparent
                     {0.5}{Hello World}
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

[1

] (Ohne Titel.aux)

 *File List*
 article.cls    2014/09/29 v1.4h Standard LaTeX document class
  size10.clo    2014/09/29 v1.4h Standard LaTeX file (size option)
transparent.sty    2016/05/16 v1.1 Transparency via pdfTeX's color stack (HO)
   ifpdf.sty    2017/03/15 v3.2 Provides the ifpdf switch
   babel.sty    2018/01/04 3.16 The Babel package
 ngerman.ldf    2016/11/02 v2.9 German support for babel (new orthography)
 ***********

 )

Unfortunately I am not able to fix this issue. :/
I am using Texpad on MacOS.
Am I right, that the problem is that pdfTeX is running in DVI mode (which compiles the tex first to a dvi and then to a pdf file) and the transparent package cannot be used in this mode? So I have to switch directly to pdf mode?
I cannot find any settings in Texpad to do so.. :/
Can you help me? Thank you in advance!


text:
Q: GcmTaskService may be blocking Exact Target push service We have a service which extends GcmTaskService and declared that as a service in an AndroidManifest as
<service
        android:exported="true"
        android:name=".MyService"
        android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE">
        <intent-filter>
            <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY">
            </action>
        </intent-filter>
    </service>

When i have this service Exact Target EtPush Service doesn't post the registration event but when i remove this service the registration works so i am assuming that our service is blocking your ETPushService which shouldn't happen.

A: ETPushService extends GcmReceiver (by Google).  In GcmReceiver there is code that looks for services and executes against the service found at index 0.  I have filed a bug report for this, but there is no fix.
Workaround:
Manually define the ETPushService in your manifest and ensure it appears before any other service.
<service
    android:name="com.exacttarget.etpushsdk.etsdk.ETPushService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</service>

This will not affect any of your other services as this will only be called when a push message is received.


text:
Q: How to Fetch values from WP database based on selected option value by onchange using PHP? I have retrieve data from WP db and display in select list.
But I cant able to store the selected option value in php variable. And I cant able to display data based on selected value. The data should be displayed when the select box is changed (onChange)
<select id="mySelect" name="taskOption">
<option>Choose Your Area</option>
<?php
      $results = $wpdb->get_results( "SELECT * FROM $table_name");
        foreach ( $results as $result ) {
            echo '<option  value="'.$result->id.'">'.$result->area_name.'</option>';
        }
      ?>
                 </select>

A: You can use below example to use Ajax in wordpress. This article explains it quite nicely.

*

*Main jquery function to use
wp_enqueue_script( 'ajax-scripts', url-to-your-file/plugin-ajax.js', __FILE__ ) , array( 'jquery' ), '1.0.0', true );

jQuery(function($) {
$(document).ready(function(){
$('#mySelect').on( 'change' , function(){
    var newValue = $(this).val();
    $.ajax({
        type: 'POST',
        url: ajaxurl, // use ajax_params.ajax_url if using in plugin
        dataType: 'json',
        data: {
            action: 'yourFunction',
            newValue: newValue
        },
        success: function(response) {
            console.log(response);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
      })
    })
   })
  });

*Hook your function
add_action( 'wp_ajax_yourFunction', 'yourFunction' );
function yourFunction(){
    $newValue = $_POST['newValue'];
    //Query whatever you want to with the $newValue
}

If you're using it in a plugin then you'll need to localize your script first.
//Localize the script for ajax purposes
wp_localize_script(
     'ajax-scripts',
'ajax_params',
array(
    'ajax_url' => admin_url( 'admin-ajax.php' )
)
);


text:
Q: How do I pipe the output of a file to a command? I'm trying to do something a bit like:
cat my_key.pub | send_key_to_server

It led me to try experiment as such:
cat my_key.pub | echo

which produced no output.
Finally I tried:
echo "hello" | echo

which also produced no output. I would have expected it to say "hello". Why doesn't this work?

A: try
cat my_key.pub | xargs echo


text:
Q: Unable to extract data using Scrapy I'm trying to extract Pre open stock market data of NSE(India). I'm able to fetch the data from the scrapy shell but when I run it as a file or run it in pycharm as a whole code I'm not getting any output. My code is
class PreopenMarketDataSpider(scrapy.Spider):

    name = 'preopen_market_data'
    allowed_domains = ['www1.nseindia.com']
    start_urls = ['https://www1.nseindia.com/live_market/dynaContent/live_watch/pre_open_market/pre_open_market.htm']

    def parse(self, response):
        stocks = ['RELIANCE', 'TATASTEEL', 'LT']
        for stock in stocks:
            stock_url  = 'https://www1.nseindia.com/live_market/dynaContent/live_analysis/pre_open/preOpenOrderBook.jsp?param='+str('stock')+'EQN&symbol='+str('stock')
            yield Request(stock_url, callback=self.data)
    def data(self,response):
        p=response.xpath('//*[@class="orderBookFontCBig"]/text()').extract()
        yield Request(p,callback=self,meta={'Stock':p})

Why is it not fetching the data. What am I doing wrong here? Can we do this via formRequest method?

A: In the last line just print p to get the output data.
class PreopenMarketDataSpider(scrapy.Spider):

        name = 'preopen_market_data'
        allowed_domains = ['www1.nseindia.com']
        start_urls = ['https://www1.nseindia.com/live_market/dynaContent/live_watch/pre_open_market/pre_open_market.htm']

        def parse(self, response):
            stocks = ['RELIANCE', 'TATASTEEL', 'LT']
            for stock in stocks:
                stock_url  = 'https://www1.nseindia.com/live_market/dynaContent/live_analysis/pre_open/preOpenOrderBook.jsp?param='+stock+'EQN&symbol='+stock
                yield Request(stock_url, callback=self.data)

        def data(self,response):
            p=response.xpath('//*[@class="orderBookFontCBig"]/text()').extract()
            print(p)
            # yield Request(p,callback=self,meta={'Stock':p})
print output
['1975.00']
['526.00']

A: yield Request(p,callback=self,meta={'Stock':p}). This isn't how you yield output on scrapy. This is telling it to visit the url 1975.00 and if successful try to call self, which is a nonsense instruction. I'm kinda surprised that it's not throwing some kind of error.
What you want to do is create an item, put the stock value into it and yield that at item.


text:
Q: Calling from Access To Stored Procedure that Use Linked Server I have Access that is used as Front End (UI) for the users, let's call it Acc1.
Acc1, is linked to tables on SQL Server.
From Acc1 I want to call to Stored Procedure, let's call it SP1.
SP1, is a simple select on a table in Linked Server. The Linked Server is an Access DB that has only tables. Let's call this DB Acc2.
Note: In the future SP1 will query more complex query that will use table from the Acc2 and from the SQL Server database. Right now as first step I want to execute this simple select query.
When I do in SP1 a simple Select query on a table from the SQL Server table, and try to cal it from Acc1, that's work.
When I try to query the linked server table in SP1 and try to call it from Acc1 it fails with error:

When I run this SP1 from SQL Server it is working.
Any ideas why it happened? How can I do it?
Following is the code:
The SP1:
ALTER PROC [dbo].[spSpanDates_BMPWorkFlowSpanCounts]
AS
BEGIN
    SELECT *
    FROM
    [Supplemental_Form_master_tables]...[tblBPMWorkflows]
END

The code in Acc1:
Private Sub Button_BPMStartEndDatesALL_Click()
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
Dim FindRecordCount  As Long
Set qdf = CurrentDb.CreateQueryDef("")
qdf.Connect = "ODBC;DRIVER={sql server};DATABASE=PLMScheduling; SERVER=USCLES425\INST2; Trusted_Connection=Yes;"
qdf.sql = "EXEC dbo.spSpanDates_BMPWorkFlowSpanCounts"
qdf.ReturnsRecords = True
Set rst = qdf.OpenRecordset(dbOpenSnapshot)
If rst.EOF Then
    FindRecordCount = 0
Else
    rst.MoveLast
    FindRecordCount = rst.RecordCount
End If
rst.Close
Set rst = Nothing
Set qdf = Nothing

End Sub
I'm using SQL Server 2008 and Access 2010.
Thank you very much for the help!

A: The answer is very simple. When SP1 run from Acc1, SQL Server uses the permissions of Acc1. So when try to query in SP1 tables from Acc2 with the permissions of Acc1 this fail.


text:
Q: JavaScript Append New Array at The Beginning HTML list I have an object like below:
var data = [
  {item_name: 'Book', stock: 15},
  {item_name: 'Pencil', stock: 15},
  {item_name: 'Paper', stock: 3}
];

And then i generate a list with HTML from the object:
console.log(data);
var html = '';
for (var i = 0; i < data.length; i++) {
    html += '
'+data[i].item_name+''+data[i].stock+'
';
}
$('#listItem').html(html);

If i add new object, how do i put the new object at the beginning of the list ?

A: try like this.The  unshift() method adds new items to the beginning of an array.use forEach() for looping with array.

var data = [
  {item_name: 'Book', stock: 15},
  {item_name: 'Pencil', stock: 15},
  {item_name: 'Paper', stock: 3}
];
data.unshift( {item_name: 'new', stock: 10});
//console.log(data);
var html='';
data.forEach(function(element,index,array){
    html += '
'+data[index].item_name+''+data[index].stock+'
';
$('#listItem').html(html);
});

JS FIDDLE https://jsfiddle.net/b1sf7a1d/


text:
Q: UIScrollview, how to scroll a page under another window I have a UISCrollview loading webviews, as the user starts scrolling to go to the next page, I need to have the the coming webpage to scroll into the screen from underneath another UIView that is stationary, I tried changing the alpha but its not really what I am looking for. how can I accomplish that?
For example, the scroll direction is top to bottom, now I have a uiview at the top of the screen which has some static data showing ( title, location, and other text labels ), and as the user scrolls down I want the content to scroll underneath the label ui view. Hope this clarifies it.

A: If I understand this question correctly I'd say you can't do this with a UIScrollView. Instead, you could have separate views for each UIWebView and handle the panning of one view under another with a UIPanGestureRecognizer.
Also, did you know there can be conflicts when using UIWebView's inside UIScrollView's?


text:
Q: How do I get a file name from a full path with PHP? For example, how do I get Output.map
from
F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map
with PHP?

A: basename() has a bug when processing Asian characters like Chinese.
I use this:
function get_basename($filename)
{
    return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}

A: I've done this using the function PATHINFO which creates an array with the parts of the path for you to use! For example, you can do this:
<?php
    $xmlFile = pathinfo('/usr/admin/config/test.xml');

    function filePathParts($arg1) {
        echo $arg1['dirname'], "\n";
        echo $arg1['basename'], "\n";
        echo $arg1['extension'], "\n";
        echo $arg1['filename'], "\n";
    }

    filePathParts($xmlFile);
?>

This will return:
/usr/admin/config
test.xml
xml
test

The use of this function has been available since PHP 5.2.0!
Then you can manipulate all the parts as you need. For example, to use the full path, you can do this:
$fullPath = $xmlFile['dirname'] . '/' . $xmlFile['basename'];

A: $filename = basename($path);

A: You're looking for basename.
The example from the PHP manual:
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>

A: You can use the basename() function.

A: To do this in the fewest lines I would suggest using the built-in DIRECTORY_SEPARATOR constant  along with explode(delimiter, string) to separate the path into parts and then simply pluck off the last element in the provided array.
Example:
$path = 'F:\Program Files\SSH Communications Security\SSH SecureShell\Output.map'

//Get filename from path
$pathArr = explode(DIRECTORY_SEPARATOR, $path);
$filename = end($pathArr);

echo $filename;
>> 'Output.map'

A: To get the exact file name from the URI, I would use this method:
<?php
    $file1 =basename("http://localhost/eFEIS/agency_application_form.php?formid=1&task=edit") ;

    //basename($_SERVER['REQUEST_URI']); // Or use this to get the URI dynamically.

    echo $basename = substr($file1, 0, strpos($file1, '?'));
?>

A: It's simple. For example:
<?php
    function filePath($filePath)
    {
        $fileParts = pathinfo($filePath);

        if (!isset($fileParts['filename']))
        {
            $fileParts['filename'] = substr($fileParts['basename'], 0, strrpos($fileParts['basename'], '.'));
        }
        return $fileParts;
    }

    $filePath = filePath('/www/htdocs/index.html');
    print_r($filePath);
?>

The output will be:
Array
(
    [dirname] => /www/htdocs
    [basename] => index.html
    [extension] => html
    [filename] => index
)

A: There are several ways to get the file name and extension. You can use the following one which is easy to use.
$url = 'http://www.nepaltraveldoor.com/images/trekking/nepal/annapurna-region/Annapurna-region-trekking.jpg';
$file = file_get_contents($url); // To get file
$name = basename($url); // To get file name
$ext = pathinfo($url, PATHINFO_EXTENSION); // To get extension
$name2 =pathinfo($url, PATHINFO_FILENAME); // File name without extension

A: With SplFileInfo:

SplFileInfo The SplFileInfo class offers a high-level object oriented
  interface to information for an individual file.

Ref: http://php.net/manual/en/splfileinfo.getfilename.php
$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());

o/p: string(7) "foo.txt"

A: The basename function should give you what you want:

Given a string containing a path to a
  file, this function will return the
  base name of the file.

For instance, quoting the manual's page:
<?php
    $path = "/home/httpd/html/index.php";
    $file = basename($path);         // $file is set to "index.php"
    $file = basename($path, ".php"); // $file is set to "index"
?>

Or, in your case:
$full = 'F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map';
var_dump(basename($full));

You'll get:
string(10) "Output.map"

A: Try this:
echo basename($_SERVER["SCRIPT_FILENAME"], '.php')

A: $image_path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
$arr = explode('\\',$image_path);
$name = end($arr);

A: <?php

  $windows = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";

  /* str_replace(find, replace, string, count) */
  $unix    = str_replace("\\", "/", $windows);

  print_r(pathinfo($unix, PATHINFO_BASENAME));

?>

body, html, iframe {
  width: 100% ;
  height: 100% ;
  overflow: hidden ;
}
<iframe src="https://ideone.com/Rfxd0P"></iframe>


text:
Q: Retrieve the initial Options passed to the Form.Symfony2 Is there a way to retrieve the initial options passed to the FormBuilder for the creation of the form? I know FormConfigInterface has method getOptions(), but I have used that and got the resolved options of the form instead, e.g: after being normalized.
So how can I get the original options passed by the user?
//by options, I mean the $options passed here
$formFactory->create('form_name', 'form_type', $options);

then I want to access $options later in and EventListener registered to this form:
//.. in a form EventListener e.g: on preSubmit
$form = $event->getForm();
$options = $form-> ? //this is where I want to get $options that was passed above during the form's creation.

A: To achieve it with the current Form Component implementation is quite complicated, you'd need replicate the behavior of ResolvedTypeDataCollectorProxy to be able to get the "passed options" after they are resolved.
I suggest you go back to the trivial method: defines a custom form option to pass the initial options.
class CustomFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->setAttribute('initial_options', $options['initial']);

        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
            // do something with:
            $event->getForm()->getConfig()->getAttribute('initial_options');
        });
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'initial' => null,
        ]);
    }
}

So, you'd pass the "initial" option also to the form type options. Something like this:
$options['initial'] = $options;
$formFactory->create('form_name', CustomFormType::class, $options);

A: Inside your form class, you can add the following attribute and getter :
private $defaultOptions;

public function getDefaultOptions() {
   return $this->defaultOptions;
}

And, in your buildForm :
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $this->defaultOptions = $options;
    //...
}

Finally, in your EventListener :
//.. in a form EventListener e.g: on preSubmit
$form = $event->getForm();
$options = $form->getDefaultOptions();


text:
Q: Which bibliographystyle for lastchecked and URL attribute? I noticed that lastchecked and URL are non-standard attributes for a bibTeX files, which is kind of strange nowadays, but that's a different matter.
I tried to use @misc{...} with itmalpha style, but my document doesn't show the two attributes. Which style can I use for it to display, which doesn't mess up my other references, which are articles and incollections (for now).

A: In most bibtex styles the information about url and the date when the web page has been accessed can be stored in the howpublished field (in free format).
A second alternative is to modify the itmalpha style to accommodate the two fields. The styles does not support url and lastchecked. Thus the first step is to insert these two fields in the ENTRY part of  the style:
ENTRY
  { address
    ...
    lastchecked
    url
    ...
  }
  {}
  { label extra.label sort.label }

Then, we create a function to print the value  of the fields. Thus we insert the following code in the file
FUNCTION {format.url.lastchecked}
{
  url empty$
    'skip$
    { "Available at: \url{" url * "}" *
      lastchecked empty$
        'skip$
        { "Accessed on: "  lastchecked * }
      if$
    }
  if$
}

Finally, we have to use the function at the appropriate position (in the definition of misc). We can replace the  definition of misc with
FUNCTION {misc}
{ output.bibitem
  author empty$                               % added by R.Bless
    { format.editors output.nonnull }          % added by R.Bless
    { format.authors "author" output.check }   % added by R.Bless
  if$
  title howpublished new.block.checkb
  format.title output
  howpublished new.block.checka
  howpublished output
  organization output
  institution output
  format.date output
  fin.entry
  format.url.lastchecked output
  new.block
  note output
  fin.entry
  empty.misc.check
}

Instead of editing the itmalpha.sty file, please make a copy, edit it, and rename it (e.g. myitmalpha.sty).
PS I have used \url{} to wrap the value of the bibtex url field, this requires to load an appropriate style, e.g., url or hyperref.

A: all styles here http://archiv.dante.de/~herbert/Bibliography/ know the fields url and urldate


text:
Q: Can a wifi AP act as a client, and a server at the same time?
I feel this is SF worthy (as opposed
  to SU) as I go into a bit of
  detail on gateways/routing.

Here's my ideal setup (if possible) -- there is a wifi network (lets call it bob's) with which I want access to, but I have a few other wifi-connected computers on my network which I want to keep behind a firewall.
So I was thinking of buying a wireless access point so that I could set it up to connect to bob's network from the AP, and then from my server, connect to the AP via ethernet. So that's the first bit. Second part is that I want to have my own private wifi network off the back of this; can I then tell the AP to serve a new network called foobar.
When I say private network, I mean that my server is actually a Debian linux install with routing configured (and I also do some QoS stuff on, etc). So ideally, I'd like all the clients on the private network to be behind the server in terms of routing. However, if the private clients connect to the server via wifi, then aren't they exposed to the "public" network? That is, if someone is savvy enough to scan for my IP range.
Also, to do routing I'd need to connect two ethernet cables between the server and the AP (because you can't do routing/QoS on virtual devices) -- which isn't a problem really; but I'm not sure whether the AP will allow me to separate the public and private LANs.
Or, as well as the AP, am I better getting a wifi-to-ethernet adapter for the server? I could use a wifi usb, but this can be tricky to set up on headless linux; plus the signal strength is a bit lousy. I cannot use a PCI card because the server is a micro ATX Atom PC.
If this question is a bit vague/spurious in places, please comment and I will explain in more detail.

A: Yes there is some wireless hardware can do this.  If your AP only has one radio it will likely cost you in performance.  APs with multiple radios tend to support setting up multiple SSIds.  With the right hardware something like dd-wrt can be used to accomplish this pretty easily.


text:
Q: select query with array I have a table dbo.comp has id and name as columns.
dbo.comp
 Name       id
 A           1
 B           2
 C           3
 D           4
 E           5

Where B &D is parent name inserted from excel sheet .
excelsheet
 parent
   B
   D

I need to find out what are the Id's for the parent names in dbo.comp. For that I stored parent which is present in the excel sheet into a array called parent[j]. And trying to compare with the id presents in the dbo.comp like this. But its not working
String Querystring7="SELECT Id from dbo.Comp where Id="+Parent [j]+" ";

am writing in java program I stuck writing query for this. How can I get parent name id from dbo.comp by comparing the parent[j] array? Please help me to write a query

A: Parten [J] returns the letter B or D doesn't it?
If so - the query should be something like this...
"SELECT id FROM dbo.comp WHERE NAME = '" + Parent[j] + "'"

A: Since you are storing the NAME in the Excel spreadsheet, you should be using the name to query your table, not the ID, as you are doing.
Example:
String Querystring7="SELECT Id from dbo.Comp where Name='"+Parent [j]+"' ";


text:
Q: Using google oAuth2 to collect gmail email from java app I have a web base email client that uses a java app to connect to IMAP and POP3 servers to download email. There is an issue that if a user usually logs in form the US that the java app will not have access to collect emails until that user logs in from the same county the java app is running.
I was told to overcome this to use google oAuth in order for the account user to give permission to my app to collect emails. Is this correct? Once this has been accomplished I would also like to the the API to import contacts, but for now authorization/authentication is sufficient.
The problem I am facing is that after trying to make heads a or tails of the google oAuth api documentation im really confused and did not yet manage to make a working example. Documentation often has links to a depreciated API and there is no example with a dowload link to both the API needed and exaple source code, as a result I think im using incorrect libraries for my examples.
Its also not clear to me what/how to accomplish what is needed do I use client authentication via javascript to create a popup whereby the user grants access?
Or do I use installed app client with a token and secret, this is what I tried but the 'command line' example I tried requires Java EE and this is a native app so I dont see why and I dont want to import all Java EE libraries to my small email downloader app.
Where can I find more intuitive documentation and working examples on this?

A: If you stay away from OpenID 2 and OAuth 1, I think the docs are pretty orderly these days.  The best place to start is https://developers.google.com/accounts/docs/OAuth2


text:
Q: Will calling Console.WriteLine() for a long running console application cause memory issues? I have a .NET Console application that runs for days and writes to its window using Console.WriteLine().
I am concerned that this will ultimately cause a memory issue. Is that correct?
Assuming I want to write to the console window in this fashion is there something I can do to "clear" the console window buffer of messages and reduce memory consumption periodically?


text:
Q: Nth-child selector in Bootstrap 3 I have this page structure

TEXT

TEXT

TEXT

TEXT

TEXT

All elements here are floating left, what i need is that every second picture element float right?
I have tried with div:nth-child(odd) but then all picture are floating right, i need every second picture to float right? Is there solution with simple CSS??

A: the following does what you are asking for :
.pictures-page *:nth-child(4n+1) img{float:right;}
.pictures-page div:nth-child(2n+1){clear:left;}

but I'm guessing you are really wanting are the images alternating at the left and right edges of the page:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title></title>

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

TEXT

TEXT

TEXT

TEXT

TEXT


text:
Q: XML in Delphi 7; worded better Okay, so I'm now aware of the fact I need to use TXMLDocument to open a .xml in Delphi 7, but I had a few further questions (hopefully answerable ones that haven't already been answered, I didn't see anything that looked overly helpful)

*

*If I run tempdoc.LoadFromFile('document.xml'); - just as an example, it throws up an Access Violation, but I'm not sure what I'm doing wrong there. I looked it up, and the violation ends in 00000000, which indicates that it's not able to find the file, which is why I wanted to ask - Do I need to put the entire filepath in the LoadFromFile('')?

*If so - I tried to use tempdoc.LoadFromFile(tempbuffer+'shared.xml') - where Tempbuffer is the extracted filepath of everything up to that (in this case 'C:\users\...\Appdata\Roaming\Skype\')

*I assume, like before, I'm using the part in the wrong way, but as I keep having to point out, this is all new to me. What am I doing wrong here? Is it because of the location of the file, or something else?

*I haven't yet investigated it properly, because I'm still trying to work out how to actually read the .xml file, but I assume there's a way I can extract the  child node from this:

<?xml version="1.0"?>
<config version="1.0" serial="56" timestamp="1412085296.3">
    <Lib>
    <Access>
        <Cookies>4100</Cookies>
    </Access>
    <Account>
        <Default>[ACCOUNTNAME]</Default>
    </Account>
    </Lib>
</config>

I'm trying to extract the [ACCOUNTNAME] field from the  subnode. Hopefully this is clearer than the previous attempt.
Short version: How does LoadFromFile work? Can I extract a field from a node and turn it into a string?

A: The reason why you are getting the Acces Violation on
tempdoc.LoadFromFile('document.xml');

is most likely the fact that TXMLDocument has not been created yet, such as by
tempdoc := TXMLDocument.Create(Form1);

Or dropping a TXMLDocument component onto the Form at design-time.
Then you can call
tempdoc.LoadFromFile('document.xml');

Or, if you want to load an existing file right away, by
tempdoc := TXMLDocument.Create('document.xml');

But then tempdoc1 **MUST** be declared asIXMLDocumentinstead ofTXMLDocument`.
The only time when you do not need to create TXMLDocument in code is if you have placed it onto the Form from Component Palette, then it gets automatically created with the Form.
BTW when an access violation occurs at address 00000000, it means you are trying to acces a nil pointer, such as an uninitialized object, or an already freed object.


text:
Q: How can I output values for time intervals with no data in QuestDB I am using QuestDB to get the amount of events we are receiving every 500 milliseconds. Everything works as expected and I can use SAMPLE BY 500T to aggregate in half a second intervals.
However, for the intervals where we don't have any data, we are not getting any rows. I guess this is expected, but it would be good to have some way of getting a row for those intervals just with null or empty values.

A: Luckily in QuestDB you have the FILL keyword to do exactly that. Take this query running at the public QuestDB demo:
SELECT
    timestamp, count()
FROM trades
WHERE timestamp > dateadd('d', -1, now())
SAMPLE BY 500T ALIGN TO CALENDAR;

In this case I am aggregating every 500 milliseconds and getting results only for the intervals where I have data. I am limiting to only the past day. You can run this on the demo site as it is a live dataset and you should see gaps for some intervals.
Now, by using FILL I can add the rows for the periods with no values
SELECT
    timestamp, count()
FROM trades
WHERE timestamp > dateadd('d', -1, now())
SAMPLE BY 500T FILL(NULL) ALIGN TO CALENDAR;

Note that you could also fill with LINEAR (linear interpolation of previous and next rows), PREV for the value of the row before, or with a constant value.


text:
Q: Can not show view I want to show my custom view when there is no network connection.
Something like this:

I have a ViewController inside a NavigationController
in AppDelegate I write like this:
var statusView: NetworkStatusView?
...

func showNetworkStatusView() {
        if statusView == nil {
            statusView = NetworkStatusView()
            if let statusView = statusView {
                let screenSize = UIScreen.mainScreen().bounds
                statusView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: 60)
                statusView.hidden = false
                if let rootViewController = window?.rootViewController {
                    rootViewController.view.addSubview(statusView)
                }
            }
        }
    }

and In my ViewController, I call like this:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.showNetworkStatusView()

But it doesn't show my custom view. I've also try view.addSubView(statusView) in my ViewController, but doesn't work also.  I make sure that the function is called, because I debugged.
Here is my NetworkStatusView:
import UIKit

class NetworkStatusView: UIView {

    @IBOutlet var contentView: UIView!
    @IBOutlet weak var statusImageView: UIImageView!
    @IBOutlet weak var statusLabel: UILabel!

    required override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initSubviews()
    }

    func initSubviews() {
        let nib = UINib(nibName: "NetworkStatusView", bundle: nil)
        nib.instantiateWithOwner(self, options: nil)
        contentView.frame = bounds
        addSubview(contentView)
    }

}


text:
Q: Как рисовать в фотошопе 8-битные картинки? Мне нужно нарисовать декорацию для 8-битной игры, но все картинки получаются с глубиной цвета 32 бита. Пробовал менять разные настройки в фотошопе (изображение- режим- 8бит/канал) но картинки все равно 32-битные.

A: Фотошоп разный бывает. Я распишу для Adobe Photoshop CC 2018. Итак, по шагам...

*

*Создаем сперва новую картинку заданной геометрии. Файл → Создать, там выбираем Цветовой режим RGB 8бит

*После создания новой картинки - сразу же меняем цветовой режим. Изображение → Режим → Индексированные цвета. В открывшемся диалоге меняем Палитра, допустим на Системная (Windows) или Равномерная (про использование преобразования в индексированные цвета - подробнее можно почитать тут):

*Начинайте рисовать. При выборе цвета обращайте внимание, что не все цвета на цветовом кубе доступны (из-за выбранной битности), это можно увидеть в предупреждении и предложении ближайшего возможного цвета:

*При сохранении нарисованного файла Файл → Сохранить как... смело выбирайте формат GIF. Этот формат как раз представляет 8-битную картинку. Можно выбрать и формат BMP, но тогда нужно будет дополнительно указать Глубина 8-бит:

Бинго!


text:
Q: Animate width of button when text changes I want to animate the width of the button when the text of it changes. I know I can't use width auto to do this.
My idea was to basically useRef on the button itself, to get the clientWidth of it, and then change a CSS variable to put that width. Then I would use that variable to define the width.
For some reason, the width gets set correctly, but the animation doesn't work. If I edit the CSS on Chrome Developer Tools and change the width from 200px to 400px it works... But when I set it back to the CSS variable and then change the inner text, even though the CSS variable gets updated correctly, the animation doesn't work.
.button {
width: var(--buttonwidth);
transition: width 2s ease-in-out;
}

// When children(text) changes, update css variable
  useEffect(() => {
    const buttonInnerWidth = buttonRef.current.clientWidth;
    document.documentElement.style.setProperty(
      '--buttonWidth',
      `${buttonInnerWidth}px`
    );
    console.log(buttonInnerWidth);
  }, [children]);

Does anyone have a better idea of how to do this?

A: this is a simple example that changes button width when clicking on that. you can change this listener to anything else you want
example code:

$(document).ready(function(){
$("button").css({"width":$("button").text().length*10});
  $("button").click(function(){
    var str = " activated ";
    var strWidth = str.length*10;
    $(this).css({"width":strWidth}).text(str);
  });
});
button{
height: 40px;
transition: 0.4s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>press</button>

A: This is another way too. Almost same as Hooman Namazi's solution, but little bit different approach.
Check this out:

jQuery(function ($) {
  $("button").css({"width":$("button").text().length*10});
    var text = ['first text', 'this is second text', 'and this one is third', 'Hi, I am forth'];
    //used to determine which is the next text to be displayed
    var counter = 0;
    var $button = $('button');
    //repeat the passed function at the specified interval - it is in milliseconds
    setInterval(function () {
        //display the text and increment the counter to point to next text item
        $changeText = $button.text(text[counter++]);
        $button.css({"width":$("button").text().length*10});
        //if it is the last text item in the array point back to the first item
        if (counter >= text.length) {
            counter = 0;
        }
    }, 2000);
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  transition: 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>first text</button>

A: I didn't want to use JS to fix this has performance wise it wouldn't be great to keep checking the width of the text inside the button. Ended up using width: auto and changing the max-width when I change the text inside the button.
Not the perfect solution because you can't give it super long text, but for my use case it works nicely :D
Here you go:
.button {
   width: auto;
   white-space: nowrap;
   max-width: 15rem;
   transition: max-width 0.3s cubic-bezier(0.445, 0.05, 0.55, 0.95);

   &.loading {
     max-width: 30rem;
    }
}


text:
Q: How to use a database across two availability zones I have servers in the USA and Japan for my website. At the moment they are both connecting to a MySQL server in the USA, which is obviously perfect for my local USA clients but quite slow for my Japanese clients.
What is the best strategy for reducing latency? How can I introduce a local MySQL server for the Japanese end and sync these up?
I have considered master-master replication but this appears to be an incomplete and unstable solution. Are there any other suggestions?


text:
Q: How to run a specific scenario from the feature file using Runner.runFeature? I have a scenario where there are many scenarios in the setup.feature file and I only have to execute one. If I remove all scenarios and only keep one it works fine as per my requirement. But in that case I have to create a duplicate feature file for each API which doesn't seem right.
Map<String, Object> var = new HashMap<>();
Map<String, Object>testing =  Runner.runFeature("classpath:jtr/setup.feature",var,true);

What I tried and didn't work. Is there a way to only run a particular tag in the feature file?
Map<String, Object>testing =  Runner.runFeature("classpath:jtr/setup.feature",var,true).tags("@smoke");

A: See if this works:
Runner.runFeature("classpath:jtr/setup.feature@smoke", var, true);

If that doesn't work there are no plans to fix it. In my opinion Runner.runFeature() is a "legacy" API created in the early days only for calling a Karate feature from Java, that we plan to deprecate.


text:
Q: What is the correct term for this root directory in web development? I am writing some documentation for a web application and I want to make sure I am using the correct terminology in describing this root directory.
My web application can be configured to be used in any directory. For example you could install it at http://site.com/, or you could install it at http://site.com/mydir/, or you could install it all http://site.com/dira/dirb/.
In each of those cases the root directory would be /, /mydir/ and /dira/dirb/. My question is, is there a term for this exact type of absolute root directory concept? Document root? application root? web root? Or is this a special type of root that is specific to my application that I should invent a name for?

A: I would say web application root, which is the term used on MSDN for the directory where web.config resides.
The web site root is always '/', but in IIS any subdirectory can be configured as an own application, with its own web.config and it is then logical to call that directory for the web application root.
If your application does not have an own web.config I would suggest using "install root" or something like that to avoid confusion.

A: I refer to it as a [web]application root -- the root of that particular application.
It is the root of the application, but not necessarily that of the web(site), depending on how that is defined. In a different environment, however, a Site and a Web have very specific meanings. In SharePoint, for instance, a "Web root" relative path might be "/mysite/myweb". A "document root" sounds like a place to find documents ... not an application.
The important thing is that the users knows what is meant -- and to this effect I'd recommend clearly separating the concerns of "web"/"document" and "application".
Happy coding.

A: / is commonly referred to as web root, and application root can be seen as something like the following: /application-directory. You can however call the both the examples root, as they surely are the root of something (in this case, your web application and/or server).


text:
Q: Which vectors have unique representation when it isn't a direct sum? I know that $V = U \oplus W$ means that every $v \in V$ can be written uniquely as $v = u + w$ for some $u \in U, w \in W$. However, what happens if $V = U + W$ is not direct? Then this means that some vector $v$ does not have a unique representation. But can we say exactly which vectors have a unique representation, and which don't?
Is this even a useful question? Intuitively, I am thinking "sometimes we don't have a direct sum, but perhaps we can still work with what we've got. In particular, let's see which vectors we can write uniquely, and maybe we can work with those."

A: If one vector can be written in more than one way, then all can. Let $v=u+w$ for different pairs $\{u,w\}$ and write $x=(x-v)+v=(u'+w')+(u+w)=(u'+u)+(w'+w)$.

A: If $V=U+W$ is not direct, then there is $z \in U \cap W$ with $z \ne 0.$
Let $v \in V,$ then there are $u \in U$ and $w \in W$ such that
$$v=u+w.$$
We also have
$$v=(u-z)+(w+z).$$
Observe that $u-z \in U, w+z \in W, u-z \ne u$ and $w+z \ne w.$
Consequence: each $v \in V$ does not have a unique representation.

A: First note that the difference between $U\oplus W$ and $U+W$ is that in the latter case we allow $U\cap W$ to be non-trivial. So there exists a $v\neq 0$ such that $v\in U\cap W$ so we can write $v=v+0$ and $v=0+v$.


text:
Q: Access multiple included layouts from a different xml file I'm trying to access a TextView from an included layout but I don't know how.
This is the layout I setContentView(R.layout.activity_home); on my onCreate:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"

        app:menu="@menu/activity_home_drawer" />

</android.support.v4.widget.DrawerLayout>

You can see that this layout includes another layout, app_bar_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.branco.sauce.home">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_home"
        android:id="@+id/includeContentHome"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Now this other layout includes my final xml file, the one I have a TextView, content_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.branco.sauce.home"
    tools:showIn="@layout/app_bar_home"

    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ROLA 3"
        android:textSize="100px"
        android:id="@+id/txtRola3"
        />
    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"

        />
</RelativeLayout>

What I want is to access the TextView which id is txtRola3 in the following method:
@Override
        protected void onPostExecute(Void result) {

            final LayoutInflater inflateContentHome = getLayoutInflater();
            final View viewContentHome = inflateContentHome.inflate(R.layout.app_bar_home, null);
            TextView txtTest = (TextView)viewContentHome.findViewById(R.id.includeContentHome).findViewById(R.id.txtRola3);
            txtTest.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    System.out.println("You clicked on the textview");
                }
            });
}

As you can see, I've tried inflating some layouts but I have no idea how to make this work. I mean, I can see the TextView and it's text, but the listener is not working. I'm accually doing this so I can learn and access my ListView(which right now I can't populate with data). I know this kind of question has been answered before, but since I have three layouts and one includes the other, I couldn't get any luck with others answers.
EDIT: home.java:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        new RemoteDataTask().execute();
    }
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {

        protected void onPostExecute(Void result) {
            final LayoutInflater inflateContentHome = getLayoutInflater();
            final View viewContentHome = inflateContentHome.inflate(R.layout.app_bar_home, null);
            TextView txtTest = (TextView)viewContentHome.findViewById(R.id.includeContentHome).findViewById(R.id.txtRola3);
            txtTest.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    System.out.println("You clicked on the textview");
                }
            });
}
}

OBS: My code has roughly 800 lines, so I added here what matters the most.

A: As it turns out, I don't need to create an inflater, assuming all three layouts are 'connected'. All I did was findViewByID as if my textview was on the main layout.
    protected void onPostExecute(Void result) {
                TextView k = (TextView)findViewById(R.id.rola3);
                k.setOnClickListeer...
}