text:
Q: Essential roles for web application team Some friends of mine came up with an idea for a web application which we (so far) think could be great. I made the analysis and all the early stages of the development process and I'm about to start the coding. I'm talking about something that is barely a mid-level project, so I consider one developer (myself) should be enough.
The thing is that we are trying to assign roles to each one of us so we can be focused on our duties and have clear our responsibilities within the team. We are a crew of four people, three of us (my friends) are business people who would do the marketing, customer relationship, management and accounting stuff and I'm basically the developer. I have in mind to get them involved into the development process by giving them documentation to write and use them as testers, all of that besides the management duties they have.
Perhaps someone out there have been in the same situation, so I would appreciate if the experience is shared so we can effectively give ourselves positions in the project based on what I explained above. Which are the essential roles or the optimal team layout so the idea can be developed successfully? The question is not strictly about programming, but it's related to build a software entrepreneurship beyond the code, that is something that I'm sure plenty of us are looking.
Any help is really appreciated! Regards.

A: I think you're on the right track. What I tend to do is think about responsibilities in terms of "functional" vs "technical" and go from there. "Functional" responsibilities and requirements reflect the customer, the user, the stakeholders and are usually technology agnostic. "Technical" responsibilities and requirements translate the functional items into architectures, platforms, technical relationships, coding languages, etc.
Here are some possible functional roles your partners can fill to support your development role:
Project Manager: Ultimately responsible for timelines, budgets, and delivery of projects / sprints and product delivery.
Business Analysts: Collect customer requirements for the software. This role usually requires subject matter and market expertise or access to such expertise. They ultimately write the functional specs that your technical specs will be derived from.
Product Manager: This role compliments the marketing efforts by ensuring that first and all future iterations of the product are meeting market and customer needs. They have full responsibility for bridging that gap between functional and technical.
I think what you mentioned about also using them to write documentation and test is a great idea, as it will help them understand the development time and effort required from your job, and allow them to speak intelligently to the more technical aspects of the product, even if they are not techies themselves.
They could also play a big role in helping construct the user experience, by storyboarding and wire-framing.
Good luck!


text:
Q: How can I make a Search bar form that overlays other HTML elements? I am trying to make a search bar that appears by overlapping other elements of the web page. A good example of what I am trying to achieve would be at this Page
As you can see when the search icon is pressed it pops up on the whole screen.
I have tried doing something like this:

            <form action="search.php" method="post">
              <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
            </form>

And the css:
.search-overlay {
width: 100%;
position: fixed;
z-index: 99999;
top: 0;
left: 0;
background-color: rgba(16,37,66,0.9);
}

body {
background-color: #F5F5F5;
color:#F87060;
height:1000px;
/*background-image: url(res/imaage.png);*/
}

.orange-search {
/*this is the search bar inside and I know */
/*the display is hidden but I have jQuery code that changes that*/
display: none;
width:21%;
position: absolute;
left: 39.6%;
top: 48%;
}

When I do that I get an actual background behind all of the other elements.I will be happy with any working way to this.
P.S. Sorry for my very bad English it is not my first language and I am doing my best.

A: I changed i few things in your css which will allow the search bar to be displayed correctly

Note:  tag should be the parent of all DOM elements

See code snippet:

.search-overlay {
  position: fixed;
  z-index: 99999;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(16, 37, 66, 0.9);
}

body {
  background-color: #F5F5F5;
  color: #F87060;
  height: 100vh;
  margin: 0;
  /*background-image: url(res/imaage.png);*/
}

.orange-search {
  /*this is the search bar inside and I know */
  /*the display is hidden but I have jQuery code that changes that*/
  width: 21%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

      <form action="search.php" method="post">
        <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      </form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL Foreign Key On Delete I am trying to figure out relationships and deletion options.
I have two tables, User and UserStaff, with a 1:n relationship from User to UserStaff (a user can have multiple staff members).
When my User is deleted, I want to delete all of the UserStaff tables associated with that User. When my UserStaff is deleted, I don't want anything to happen to User. I understand that this is a cascading relationship, but I'm not sure which way.
i.e. Do I select the existing foreign key in my UserStaff table and make it cascading, or do I create a new foreign key in User and set that to cascading?

A: From Wikipedia:

CASCADE
Whenever rows in the master (referenced) table are deleted (resp. updated), the respective rows of the child (referencing) table with a matching foreign key column will get deleted (resp. updated) as well. This is called a cascade delete (resp. update[2]).

Here, User is the master table, and UserStaff is the child table. So, yes, you'll want to create the foreign key in UserStaff, with ON DELETE CASCADE

A: It's been a while since I've used this, but here goes (btw, I use Toad for MySql - a great IDE, and it's free too - http://www.toadworld.com/Freeware/ToadforMySQLFreeware/tabid/561/Default.aspx!)
You need to add a Constraint to the User table. If you have an id column (and the corresponding foreign userid key in UserStaff) then the SouceColumn should be id, the destination table UserStaff and the destination column userid. You can then set the OnDelete action to be 'Cascade'
The other options are pretty self-explanatory - Restrict limits values to the values in the source column, Set Null sets the foreign key matches to Null and No Action does, er, nothing.
This stuff is very easy to do via the Toad IDE. I used MySqlAdmin tools for ages but recently discovered Toad (and it has diff and compare tools too!).

A: The ON DELETE CASCADE is specified on the foreign key in the UserStaff table. For additional info on foreign keys the MySQL documentation has a number of examples. The User table does not have a foreign key pointing to UserStaff, so it will not be affected by changes to the UserStaff table.

A: Yes, it's possible. You should make the FK in UserStaff table. In this way:
User Table
CREATE TABLE `User` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

UserStaff Table
CREATE TABLE `UserStaff` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `UserId` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id`),
  KEY `UserId` (`UserId`),
  CONSTRAINT `UserStaff_ibfk_1`
    FOREIGN KEY (`UserId`)
    REFERENCES `User` (`Id`)
    ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

A: The easiest way might be to make two quick tables and try it out. But since you didn't I can tell you that the outcome will be that it work the way that you want to.
When you have a table User and a table UserStaff were a field in UserStaff uses a foreign key to reference a field in User; then if you delete a record from UserStaff that will be removed  wihtout having any affect on the User table. The other way around will delete all records related to that record.
Short version: A field in UserStaff should reference a field in User with CASCADE


text:
Q: Fallback for CSS background image transition I'm using CSS transitions for the background-image property, though from what I can gather they are only supported by Chrome and Webkit (it doesn't seem to work in Safari 5.1.7). I really don't want to use jQuery for the transition since its only solution is to fade out the element (and with it the content) and fade back with a new background. Normally I would do it the standard way and have multiple divs or images inside a wrapper to rotate between, but the way this site is set up that simply wouldn't work (well technically it could, but it just seems ridiculously and needlessly over-complicated).
Visit the site here and you'll see what I mean: http://bos.rggwebdesigns.com/
Is there some way to safely fall back for other browsers that don't yet support background image transitions, either by disabling it completely or some other method? If the browser can't handle it, I don't want the user to just see the background change abruptly.

A: You can use Modernizr for feature detection, and then change your CSS on the fly accordingly.
Modernizr


text:
Q: Combine 2 PowerShell arrays I'm trying to figure out how to combine 2 arrays as explained here by Microsoft.
$Source = 'S:\Test\Out_Test\Departments'
$Array = Get-ChildItem $Source -Recurse

$Array.FullName | Measure-Object # 85
$Array.FullName + $Source | Measure-Object # 86
$Source + $Array.FullName | Measure-Object # 1

The following only has 1 item to iterate through:
$i = 0
foreach ($t in ($Source + $Array.FullName)) {
    $i++
    "Count is $i"
    $t
}

My problem is that if $Source or $Array is empty, it doesn't generate seperate objects anymore and sticks it all together as seen in the previous example. Is there a way to force it into separate objects and not into one concatenated one?

A: This is because $Source is a System.String and + is probably an overloaded for Concat. If you cast $Source to an array, you will get your desired output:
[array]$Source + $Array.FullName | Measure-Object # 86

A: In PowerShell, the left-hand side operand determines the operator overload used, and the right-hand side gets converted to a type that satisfies the operation.
That's why you can observe that
[string] + [array of strings] results in a [string] (Count = 1)
[array of strings] + [string] results in an [array of strings] (Count = array size + 1)
You can force the + operator to perform array concatenation by using the array subexpression operator (@()) on the left-hand side argument:
$NewArray = @($Source) + $Array.FullName

A: *

*Place your elements inside parentheses preceded by a dollar sign.

*Separate your elements with semicolons.

Applied to the case of the initial question:
$($Source; $Array.FullName) | Measure-Object #86


text:
Q: NASM: in/out instead of int When writing a bootloader how do you make calls to ports instead the use of interrupts (i.e. int 10h)? Is there a list someplace online I am unaware of for known vectors? Is there a place I can go to do mapping of hardware not covered by the bios interrupts (i.e. PCI - GPUs)?

A: You can communicate with I/O ports via the in & out instructions.
in dest, src: Where dest is the input; I'm pretty sure only the accumulator register can be used as the dest. The src is the port number. src can be the data register or an immediate value.
out dest, src: Where dest is the port number; this time the data register or an immediate value is used for the dest. The src is the output. src can be the accumulator register.
Given the lack of information, I'm assuming your boot loader is for the x86 and that you'll be limited more or less to 512 bytes of space. If that's the case, I would recommend using the interrupts provide for you by the BIOS until you load the kernel.
More information can be found on Wikibooks, Wikipedia, and the OSDev Wiki.

A: Well, the problem is that it is not just the mapping of hardware, as well as it is not just the bootloader in the computer.
What you are really talking about is the writing of a driver. BIOS manages the simplest devices and uses the best available methods to achieve what a programmer wants. And for the programmer there is that API to access it, which for the x86 real mode means interrupts, as they are the simplest way of doing a complete context switch.
If you still want to remain in real mode, there are several more interrupts you probably are not aware of, that can be found in somehow complete Ralf Brown´s Interrupt List.
However, PCI and GPUs works on high frequencies with lots of data, and that requires much more memory and performance, which can not be easily operated on with real mode. Protected and Long mode are the way to go.
I8086 has mentioned in and out instructions as the method of accessing devices.
Whilst this used to be true and for some devices keeps true, there are many other ways of communicating with hardware, e.g. memory mapping, DMA or communication with coprocessors. Sometimes you just use in and out to find out where device´s memory lies to access it using a memory-mapped interface. I believe PCI is one of them. These interfaces are not any more difficult to work with, but they are more effective.
You will almost immediately hit the wall called "lack of official and free documentation". You must not get disappointed by this, there is always plenty of devices that have their datasheets and programmer references freely available (let's admit that Intel has a massive documentation), although it isn't always going to be your own GPU or network card.
TL;DR: You should switch to the protected mode as soon as possible to unlock a new range of options, and then you can think of writing some drivers. OSDev Wiki is surely going to be a great resource.


text:
Q: How do I embed an After Effects animation into my website? I'm new to coding and am trying my best to learn as I go along whilst creating my personal website. My current struggle comes in the form of after effects. So I have created an animation for my websites welcome screen which includes my logo and a welcome message inside of after effects. However, I am stuck getting it from after effects into Brackets. I tried rendering it as a .mov file but this isn't really what i want. Is there a work around to this?
P.s. I have tried using the bodymovin extension but I can't get that to work for me either. Its frustrating having all the ideas and visuals but not being able to transfer them into code form. I apologise in advance if there is a simple work around that i have missed.
Many thanks!

A: Export a compressed video  - an .mp4. Then use the <video> tag to embed it:
<video src="/path/to/your/video.mp4" autoplay poster="/path/to/placeholderImage.png">Message to users here if their browser doessn't support the video tag (unlikely)</video>

Read more about the video tag here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video


text:
Q: Transforming conditional probability Does somebody know why the following equation holds?
$$P(A,B|C) = P(A|B,C) P(B|C)$$
Which rule is used? I think it is not Bayes' rule.

A: You just need to use the rule $P(Y|X) = \frac{P(Y,X)}{P(X)}$:
$$
\begin{align}
P(A,B|C) &= \frac{P(A,B,C)}{P(C)} \\
&= \frac{P(A|B,C)P(B,C)}{P(C)} \\
&= P(A|B,C)\frac{P(B,C)}{P(C)} \\
&= P(A|B,C)P(B|C)
\end{align}
$$

A: It's because:
$$
P(A|B , C) = \frac{ P(A \cap B \cap C) }{ P(B \cap C) }=\frac{P((A \cap B)|C) \cdot P(C)}{P(B|C) \cdot P(C)}=\frac{\rm{P}((A\cap B)|C)}{\rm{P}(B|C)}
$$


text:
Q: ManualResetEvent is not waiting for threadpool completion I have list of batches to process. forever.
I want to do each chunk (5) in parallel, and when it is done move to the next chunk.
for some reason, the code bellow is not waiting for the chunk to be done and continue even if it is not completed.
while (true)
{
    foreach (string[] urlsArr in chunks)
    {
        int i = 0;
        foreach (var url in urlsArr)
        {
            ThreadPool.QueueUserWorkItem(x =>
            {
                ProccessUrl(url, config, drivers[i]);
                _resetEvent.Set();
                i++;
            });
        }
        _resetEvent.WaitOne();// this is not really waiting.
    }
}

A: Have a look at the Semaphore or it's slim version. Semaphore will allow you to always have only 5 threads running. Once any of those running threads finish, it can pick up new work. This is more efficient, especially if the workload is uneven. Consider situation when 1 item takes an hour to process and the other 4 take a second. In this case the 4 threads will wait for the last one to finish before picking up any other work.
For an example, see Need to understand the usage of SemaphoreSlim.
In your code the problem is that you only have one wait handle and 5 threads. When any of the 5 running threads finish work, it will set the wait handle, hence allowing your outer loop to proceed, which starts another five threads. By now, it's possible that the first 4 threads from the inner loop could have completed and any of them could set the wait handle again! Now, do you see a problem here?
As per Hans comment, if there is a dependency between work items in a single batch, so that all of the work items must be completed before you can start a next batch you should have a look at CountDownEvent

A: Here is a version with Tasks(async/await)
while (true)
        {
            foreach (string[] urlsArr in chunks)
            {
                Task[] tasks = new Task[urlsArr.Length];
                for (int i = 0; i < urlsArr.Length; i++)
                {
                    var url = urlsArr[i];
                    var driver = drivers[i];
                    tasks[i] = Task.Run(() => { ProccessUrl(url, config, driver); });
                }

                await Task.WhenAll(tasks);
            }
        }

note that it also fixes a problem with the 'i' variable in the original code which was not incremented in a thread safe way(could be fixed with Interlocked.Increment).
If your code is not async you can wait for the tasks to finish in the thread(but this is blocking) instead
Task.WhenAll(tasks).Wait();

A: I think that you can perhaps simplify the entire thing, and leverage Parallel.ForEach() to both manage the threads AND limit the degree of concurrency to 5.
If you run the following sample code, you will see that the pretend URLs are being processed in chunks of 5 because the number of concurrent threads is being limited to 5.
If you do it like this, you will not need your own chunking logic:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main()
        {
            // Make some pretend URLs for this demo.

            string[] urls = Enumerable.Range(1, 100).Select(n => n.ToString()).ToArray();

            // Use Parallel.ForEach() along with MaxDegreeOfParallelism = 5 to process
            // these using 5 threads maximum:

            Parallel.ForEach(
                urls,
                new ParallelOptions{MaxDegreeOfParallelism = 5},
                processUrl
            );
        }

        static void processUrl(string url)
        {
            Console.WriteLine("Processing " + url);
            Thread.Sleep(1000);
            Console.WriteLine("Processed " + url);
        }
    }
}


text:
Q: ActionCable Stream only if the user is on a specific page I'm trying to implement a new feature that requires a bit of real time functionality. My project is built using Rails 5.1 and I want to achieve my goals using ActionCable.
Basically I have a dashboard with multiple widgets. Each widget displaying a certain informations like RAM & CPU usage, Git Hub Pull Requests Count, Issues Count, Honey Badger errors count, etc..
There is a Sidekiq job that runs every 30 seconds and saves the data in the DB. Right in the web page ( dashboards#show ) where the dashboard displays the widgets, I have a JS interval that pull data from the server every X (usually is set to 30s / 45s) seconds.
I want from the job to stream the values to a dashboard channel ( each dashboard will have its own channel ) using ActionCable.
My question is: how do I stream only to dashboards that are "online", how do I know if the page www.myapp.com/dashboards/1 is used?
Lets say I have 1000 dashboards, I don't want to stream data to all of the from the job, only to the dashboards that are "used".
Thank you!


text:
Q: Can't make image as a link I am using asp:Hyperlink controls to generate an image as a link.
Below is the aspx code and C# code.
<asp:HyperLink ID="mainInteractiveFileLink" runat="server">
</asp:HyperLink>

C#
mainInteractiveFileLink.NavigateUrl = thisMainInteractiveItem.linkURL;
mainInteractiveFileLink.ImageUrl    = thisMainInteractiveItem.imageFile;

I want to make the image as a link. I have tried other options like ,<image> HTML controls and imagebutton.

A: Wrap your image under your Hyperlink control:
ASPX Code:
<asp:HyperLink ID="mainInteractiveFileLink" runat="server">
  <asp:image id="img" runat="server" />
</asp:Hyperlink>

Code Behind:
HyperLink1.NavigateUrl = "http://www.google.com";
HyperLink1.ImageUrl = "http://assets.fodors.com/destinations/2869/tower-bridge-london-england_main.jpg";

And generated HTML:

Based on your code, you are generating your linkURL on your image control.


text:
Q: Regular Expression writing for known pattern with dashes I need to write a regular expression for pattern matching for VB.NET. I need to have the Regex to look for a pattern like 12345-1234-12345-123, including the dashes. The numbers can be any variation. The value is stored as a varchar. Not sure how close or far my example is below. Any help/guidance is much appreciated.
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
    Dim testString As String = "12345-1234-12345-123"
    Dim testNumberWithDashesRegEx As Regex = New Regex("^\d{5}-d{4}-d{5}-\d{3}$")
    Dim regExMatch As Match = testNumberWithDashesRegEx.Match(testString)
    If regExMatch.Success Then
        Label1.Text = "There is a match."
    Else
        Label1.Text = "There is no match."
    End If
End Sub

A: Let's break down this regex:
^\d{5}-d{4}-d{5}-\d{3}$

*

*^: Match at start of target string

*\d: match character class of digits 0-9

*-: match dash (-) character

*d: match the letter "d"

*{5}: match the preceding class 5 times

*$: Match at the end of target string.

Everything looks good to me, except you should change your plain "d" to "\d":
^\d{5}-\d{4}-\d{5}-\d{3}$


text:
Q: Cannot use duplicate identifiers in select clause in PartiQL I am trying the select attribute columns with same name from Dynamodb table.
aws dynamodb execute-statement --statement \
"SELECT id, xyz.id FROM "table_example"."indexTest" WHERE column1 IN ['A','B','C']"

I am getting below error

An error occurred (ValidationException) when calling the
ExecuteStatement operation: Duplicate identifiers in select clause

I also tried using aliases, but PartiQL does not support aliases as well. Does PartiQL allow to select columns with same name?


text:
Q: Euler and Hamilton graphs i would like to know  about this. If it is Euler and Hamilton. As i see because it is $u_0$ unti $u_{19}$ it isn't Euler. Also, it is Hamilton because if we erase the edges we see it. Is this right or wrong?
Thanks a lot.


text:
Q: Is there a way to uninstall a SPECIFIC provisioned app for all user accounts in Windows 10 using PowerShell? So I looked up on the web and found PowerShell commands to uninstall:

*

*All Windows Store apps using PowerShell for all users

*A specific app using PowerShell for current user

*All apps for current user

*All apps from system account/default profile

*All apps for a specific user without logging in to that account

But I see no way to remove a specific provisioned app for all users. Suppose I want to remove only Calculator for all user accounts, how do I do that?

A: You can use this command (tested with the calculator app on Windows 10 1709):
Remove-AppxProvisionedPackage -PackageName Microsoft.WindowsCalculator_2017.1201.1912.0_neutral_~_8wekyb3d8bbwe -Online -AllUsers

The important part is the -AllUsers switch there at the end. This removes the package from all currently existing profiles and deprovisions it so that new profiles won't have it installed. To find the full package name from a fragment, you can use this command:
Get-AppxProvisionedPackage -Online | ? {$_.PackageName -like '*calc*'} | select -expand PackageName


text:
Q: SQLAlchemy Flask, match some or all I have a list of schools (1000's) with a name, city, and state.
There are name, city and state input fields.
I want to search for schools by name. If they leave city or state inputs empty I want to search by any city, any state. If they enter the city (leaving state blank) then search by name and city. Etc etc.
Bottom line: Search with the data that is available and everything else is "any".
Is there a quick way to do this other than writing every possible combination?

A: I'm writing this as if you're using Flask-SQLAlchemy and WTForms.
...
schools = School.query

if form.name.data:
    schools = schools.filter(School.name == form.name.data)

if form.city.data:
    schools = schools.filter(School.city == form.city.data)

if form.state.data:
    schools = schools.filter(School.state == form.state.data)

# at this point schools is a query filtered with whatever was given
...

This is just an example, reword it, use filters besides equality, etc.  I have "filter forms" like this, and would put extra methods on the form, query() and filter(query).  Then they can be called like this in a view:
form = FilterForm(request.args)  # use get for filtering
schools = form.query()
if form.validate():
    schools = form.filter(schools)
return render_template('schools.html', form=form, schools=schools)


text:
Q: How to search in a JSONField for a key with spaces in Django with Postgres? Suppose I've a JSONField namely "data" defined in one of my models.py in Django. The Contents of the field is somewhat similar to the following -
{
    "name": "John",
    "email": "johndoe@foo.bar",
    "last name": "Doe"
}

I need to write a queries of the following form -
self.objects.filter(data__name="John")

How do I write a similar query for the key "last name". I'm not able to proceed since that key has a space. Was thinking of getting the data and filtering it using python, But I think there would be more efficient way to get it done.
I've not real control over the data in the JSONField. So, I can't really change the name of the key.

A: We can achieve it the following way -
lookup = "data__last name"
self.objects.filter(**{lookup: "Doe"})

A: For JSON field you can use contains:
self.objects.filter(data__contains={"last name": "Doe"})


text:
Q: How to sort structure arrays in MATLAB? I'm working with an image retrieval system using color histogram intersection in MATLAB. This method gives me the following data: a real number which represents the histogram intersection distance, and the image file name. Because they are different data types, I store them in structure array with two fields, and then I save this structure in a .mat file. Now I need to sort this structure according to the histogram intersection distance in descending order in order to retrieve the image with the highest histogram intersection distance. I've tried many methods to sort this data but without result. Please can you help me solve this problem?

A: It's also possible to sort the entire structure.
To build off of gnovice's example...
% Create a structure array
s = struct('value',{1 7 4},'file',{'img1.jpg' 'img2.jpg' 'img3.jpg'});

% Sort the structure according to values in descending order
% We are only interested in the second output from the sort command

[blah, order] = sort([s(:).value],'descend');

% Save the sorted output

sortedStruct = s(order);

A: Here's one example of how you could do this, using the function MAX instead of having to sort:
%# First, create a sample structure array:

s = struct('value',{1 7 4},'file',{'img1.jpg' 'img2.jpg' 'img3.jpg'});

%# Next concatenate the "value" fields and find the index of the maximum value:

[maxValue,index] = max([s.value]);

%# Finally, get the file corresponding to the maximum value:

maxFile = s(index).file;

EDIT : If you would like to get the N highest values, and not just the maximum, you can use SORT instead of MAX (as Shaka suggested). For example (using the above structure):
>> N = 2;  %# Get two highest values
>> [values,index] = sort([s.value],'descend');  %# Sort all values, largest first
>> topNFiles = {s(index(1:N)).file}  %# Get N files with the largest values

topNFiles =

    'img2.jpg'    'img3.jpg'


text:
Q: can't select with xml id in android As you can see I have an UpdatableView in xml file with updatable_view id, but I can't select it via findViewById. The id somehow gets removed and I don't know why. I printed out the view hierarchy and this particular view doesn't have an id. the others have of course!
what can be the problem? I've tried cleaning, rebuilding, regenerating R. nothing helps!

UPDATE
in my activity's onCreate I do this
    setContentView(R.layout.starter_activity);
    ButterKnife.bind(this);

in UpdatableView class that extends FrameLayout I do this:
public UpdatableView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    inflate(context,R.layout.torob_updatable_layout,this);
    ButterKnife.bind(this);
}

and torob_updatable_layout.xml is as simple as this:
<?xml version="1.0" encoding="utf-8"?>
<merge
    xmlns:android="http://schemas.android.com/apk/res/android">
<com.rey.material.widget.ProgressView
        android:id="@+id/progress"
        android:visibility="gone"
        android:layout_width="48dp"
        android:layout_height="48dp"
        style="@style/CircleProgressBar"
        android:layout_gravity="center"
        />
<com.rey.material.widget.Button
        android:id="@+id/retry"
        style="@style/Button"
        android:text="تلاش دوباره"
        android:layout_gravity="center"
        android:visibility="gone"
        />
</merge>

A: You have to use like below.
UpdatableView updateView = (UpdatableView)findViewById(R.id.updatable_view);

A: After hours of perplexity I found that one of my UpdatableView constructors was like this:
public UpdatableView(Context context, AttributeSet attrs) {
    this(context, null, 0);
}

instead it should've been like this:
public UpdatableView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

Jesus! Make sure to pass the attrs or you won't get an id with your view.


text:
Q: Why is my multiplication operation returning zero? I wrote my first program in c just to practice. However, I don't know why it doesn't work ? The result of socks * price; in the code snippet below is zero. What am I missing here ?
#include<stdio.h>

main()
{
      int socks;
      float price, total;

      printf("How many socks >> ");
      scanf(" %d", &socks);

      printf("What is the price for each pair ?");
      scanf(" %.3f", &price);

      total = socks * price;
      printf("\n\nTotal: %.3f", total);

return 0;
}

It is a normal multiplication; I first wanted to know how many socks did the user pay let's say 4, and the price for the single pair, let's say 100.000 per sock ( that's a lot for socks, I know, but this is just for example).
Total is a float number, therefore 4 * 100.000 = should give the total price = 400.000 but I am getting 0.

A: The Problem is an incorrect usage of scanf. We don't use the formating "%.3f" with scanf. Instead you can use it when printing the output
      printf("What is the price for each pair ?");
      scanf("%f", &price);

      total = socks * price;
      printf("\n\nTotal: %.3f", total);

A: change as follows
scanf(" %f", &price);

A: Although the format to scanf(" %.3f", &price); was invalid, the larger problem is in not using the scanf() return value
if (scanf("%f", &price) != 1) {
  handle_bad_put();
}

Without testing the result of scanf(), one does not know if price was set.  Not using the correct format could still fool a scanf() result, but with scanf() tendency for problems, testing its results  is defensive coding and should be considered obligatory.

A: your main function is returning an int so therefore
int main()
{
   ...
}

And when you get the input for price it should be
scanf("%f", &price);

A: The problem is the format for scanf, as in scanf, it should be the following:
     %[*][width][length]specifier
So you cannot use a precision field like in printf.
The resource for your reference:http://www.cplusplus.com/reference/cstdio/scanf/


text:
Q: Why do i get invalid forum in my application? I try to develop a forum but I have a problem with the key of the function index, I test if it exists and after Cakephp find that this forum doesn't exist but in my database i have the forum that exist. Every time I get "Invalid Forum" when I click on the forum link in question .I want to know why, the connections between the models are correct I think. There is something wrong, but I do not know where. thank you
TopicsController :
public function index($forumId=null) {
        //debug($forumId);
        if (!$this->Topic->Forum->exists($forumId)) {
            throw new NotFoundException(__('Invalid forum'));
        }

        $forum = $this->Topic->Forum->read(null,$forumId);
        $this->set('forum',$forum);

        $this->Paginator->settings['contain'] = array('User','Message'=>array('User'));
        $this->set('topics', $this->Paginator->paginate());
    }

Model Forum :
<?php
App::uses('AppModel', 'Model');

class Forum extends AppModel {

    public $validate = array(
        'name' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                //'message' => 'Your custom message here',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
    );

    //The Associations below have been created with all possible keys, those that are not needed can be removed

    public $hasMany = array(
        'Message' => array(
            'className' => 'Message',
            'foreignKey' => 'forum_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'Topic' => array(
            'className' => 'Topic',
            'foreignKey' => 'forum_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

}

Model Topic :
<?php
App::uses('AppModel', 'Model');

class Topic extends AppModel {

    public $validate = array(
        'name' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                //'message' => 'Your custom message here',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'content' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                //'message' => 'Your custom message here',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'forum_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
                //'message' => 'Your custom message here',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
    );

    //The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
    public $belongsTo = array(
        'Forum' => array(
            'className' => 'Forum',
            'foreignKey' => 'forum_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

/**
 * hasMany associations
 *
 * @var array
 */
    public $hasMany = array(
        'Message' => array(
            'className' => 'Message',
            'foreignKey' => 'topic_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

}

EDIT :
If i do pr($this->Topic->Forum->findById($forumId)),
I get :
Array
(
    [Forum] => Array
        (
            [id] => 1
            [name] => General Discussion
            [created] => 2013-12-06
            [modified] => 2013-12-06
        )

    [Message] => Array
        (
            [0] => Array
                (
                    [id] => 13
                    [topic_id] => 5
                    [forum_id] => 1
                    [created] => 2014-09-25
                    [modified] => 2014-09-25
                    [content] => Je répond ^^
                    [user_id] => 98
                )

        )

    [Topic] => Array
        (
            [0] => Array
                (
                    [id] => 5
                    [name] => mon topic
                    [content] => c mon topic ^^
                    [created] => 2014-09-25
                    [modified] => 2014-09-25
                    [forum_id] => 1
                    [user_id] => 98
                )

            [1] => Array
                (
                    [id] => 6
                    [name] => a voir
                    [content] => super
                    [created] => 2014-09-10
                    [modified] => 2014-09-19
                    [forum_id] => 1
                    [user_id] => 98
                )

        )

)

And the queries :
Page Introuvable Invalid forum

La page que vous avez essayez d'atteindre n'existe pas
(default) 4 queries took 0 ms   Nr  Query   Error   Affected    Num. rows   Took (ms)
1   SELECT `Forum`.`id`, `Forum`.`name`, `Forum`.`created`, `Forum`.`modified` FROM `forums` AS `Forum` WHERE `Forum`.`id` = 1 LIMIT 1      1   1   0
2   SELECT `Message`.`id`, `Message`.`topic_id`, `Message`.`forum_id`, `Message`.`created`, `Message`.`modified`, `Message`.`content`, `Message`.`user_id` FROM `messages` AS `Message` WHERE `Message`.`forum_id` = (1)        1   1   0
3   SELECT `Topic`.`id`, `Topic`.`name`, `Topic`.`content`, `Topic`.`created`, `Topic`.`modified`, `Topic`.`forum_id`, `Topic`.`user_id` FROM `topics` AS `Topic` WHERE `Topic`.`forum_id` = (1)        2   2   0
4   SELECT `Post`.`id`, `Post`.`slug`, `Post`.`name`, `Post`.`type` FROM `posts` AS `Post` WHERE `type` = 'page' AND `online` = 1 ORDER BY `Post`.`created` DESC        1   1   0

ForumsController :
<?php
App::uses('AppController', 'Controller');

class ForumsController extends AppController {

    public $components = array('Paginator');

    public function beforeFilter() {
        $this->Auth->allow();
    }

    public function index() {
        $this->Paginator->settings['contain'] = array('Topic', 'Message'=>array('User','Topic'));
        $this->set('forums', $this->Paginator->paginate());
    }

}

function index of ForumsController (where i see the forums i created and where i could click on the link) :

                            Forum
                            Topics
                            Messages
                            Activity

                        <?php foreach ($forums as $forum): ?>

                            <?php echo $forum['Forum']['id'];?>

                                <?php
                                echo $this->Html->link('
'.$forum['Forum']['name'].'
',
                                                        array('controller'=>'topics','action'=>'index',$forum['Forum']['id']),
                                                        array('escape'=>false));
                                ?>

                            <?php echo count($forum['Topic']);?>
                            <?php echo count($forum['Message']);?>

                               <?php
                               if(count($forum['Message'])>0) {
                                $message = $forum['Message'][0];
                                echo $this->Html->link($message['Topic']['name'],array('controller'=>'topics',
                                                                                'action'=>'view',
                                                                                $message['Topic']['id']));
                                echo ' ';
                                echo $this->Time->timeAgoInWords($message['created']);
                                echo ' par ';
                                echo $this->Html->link($message['User']['username'],array('controller'=>'users',
                                                                                'action'=>'profile',
                                                                                $message['User']['id']));
                               }
                               ?>

                        <?php endforeach;?>

                    <?php
                        echo $this->element('paginator');
                    ?>


text:
Q: SwiftUI: Modifier inside Array I'm currently trying to put all possible modifiers directly into an array and then call them via forEach. It works with most of them too, unfortunately with frame (height, width, alignmet) not as I would like. Text and frame should align at the same time. But no matter how I try, it doesn't work. In addition, I also fail to integrate .bold and .italic in this way.
I am aware that there are other ways. If it is possible in any way, I would like to be able to include all modifiers in this way. Is that even possible?
import SwiftUI

struct Tests: Identifiable {
    var id: Int
    var text: String
    var textcolor: Color
    var textfont: Font
    var height: CGFloat
    var width: CGFloat
    var alignment: Alignment
    var textbackcolor: Color
    var corner: CGFloat
    var show: Bool
    var user: String
}

struct ContentView: View {

    @State private var testvar = [
        Tests(id: 000, text: "Hello World 1", textcolor: .red, textfont: .title, height: 100, width: 300, alignment: .trailing, textbackcolor: .blue, corner: 20, show: true, user: "System"),
        Tests(id: 001, text: "Hello World 2", textcolor: .green,  textfont: .largeTitle, height: 100, width: 300, alignment: .center, textbackcolor: .black, corner: 50, show: true, user: "George"),
       ]

    var body: some View {
        NavigationView {
            VStack {

                    ForEach(self.testvar) { txt in if txt.show == true {
                        Text("\(txt.text)")
                            .frame(width: txt.width, height: txt.height, alignment: txt.alignment)
                            .font(txt.textfont)
                            .foregroundColor(txt.textcolor)
                            .background(txt.textbackcolor)
                            .cornerRadius(txt.corner)
                        //.bold?
                        //.italic?
                        } }
               }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: Changing the order of modifiers (italic or bold must have to be applied on Text only)
ForEach(self.testvar) { txt in if txt.show == true {
    Text("\(txt.text)")
        .bold()
        .italic()
        .frame(width: txt.width, height: txt.height, alignment: txt.alignment)
        .font(txt.textfont)
        .foregroundColor(txt.textcolor)
        .background(txt.textbackcolor)
        .cornerRadius(txt.corner)
    }
}

on data
@State private var testvar = [
        Tests(id: 000, text: "Hello World 1", textcolor: .red, textfont: .title, height: 100, width: 300, alignment: .trailing, textbackcolor: Color(.blue).opacity(0.2), corner: 20, show: true, user: "System"),
        Tests(id: 001, text: "Hello World 2", textcolor: .green,  textfont: .largeTitle, height: 300, width: 300, alignment: .center, textbackcolor: .black, corner: 50, show: true, user: "George"),
       ]

I've got

If you are wondering why .largeTitle is not italic, please see
How to apply .italic() to .largeTitle Font?
UPDATE to reflect discussion
to be able to modify the style based on values in your array, use simple Text extension
extension Text {
    func style(bold: Bool = false, italic: Bool = false) -> Self {
        var s = self
        if bold {
            s = s.bold()
        }
        if italic {
            s = s.italic()
        }
        return s
    }
}

which is (I hope so) self-explanatory


text:
Q: HTML Javascript forms, and a php script - Simple question, help! what does this code do? So I have this simple form:
<form action="includes/process.php" method="post" name="standard_use" id="standard_use" enctype="multipart/form-data">

        <button onclick="dofunction(); return false;">Do it!</button>

        <input type="file" id="upload_file" name="filename" style="float:left;width:70%;" size="42"/>

</form>

So what happens really when the button is clicked ?
Is it that the php file is called ? does it not ? the javascript is called before ?
Anyone can shed some light on this ?
Thanks !

A: Well, when you hit the button the following events occurs:

*

*You send a REQUEST to the server

*The php codes evaluates the request and runs some codes

*Finally it returns back a RESPONSE which you see as a web page

Javascript is a client-side script which means that whenever you make an action on the page, the code runs. For instance, when you click the button, before sending the request javascript will work. You may, for instance, place a function that will be triggered when you hit the button which checks the form and either approves the form or shows the error messages
EDIT
As far as your comment is concerned:
Yes, javascript runs first when you hit the submit button. Php runs only when you submit the form and make a request to the server.
Consider this example: (I am better at explaining things with examples:)
<form action="somepage.php" onsubmit="return checkMe()" method="POST">
    <input name="firstname" id="fn" value="" type="text" />
    <input type="submit" value="Submit" />
    <script type="text/javascript">
          function checkMe(){
              var tb = document.getElementById("fn")

              if(tb.value == "Alex") return true;
              else return false;
          }
    </script>
</form>

So basically, when you hit the button and try to submit the form, the javascript will first check whether the name provided in the textbox is Alex or not, if it is not then it will not submit the form. If it is Alex then it will submit the form and then the form will redirect the user to somepage.php. Finally, the php codes will work in somepage.php and the page will be rendered again.

A: What happens is that only doFunction() javascript function is invoked and nothing more.
However, it might be possible that this javascript function invokes "submit" event on the form and the request is sent (what you described as "php file is called").

A: Your code just trigger javascript event and your function. To submit a form you need an
<input type="submit" value="Submit" />

or a button, which default type is submit (thx davin)
<button value="Submit" />

However as far as you return false in your javascript code your form won't be submitted even with the submit button.


text:
Q: Как копировать файлы из одной папки в другую, указав её полный путь Прошу мне помочь с решением проблемы. Представим ситуацию, что есть exe (скомпилированный .py файл) и папка "files", где находятся какие-либо файлы. А есть ещё папка "end", которая находится, к примеру, на другом локальном диске. Как скопировать через Python файлы из папки "files" и, указав полный путь (C:....), вставить это в папке "end" (если требуется, то с заменой). Это может пригодится на пример с установкой модов во всякие игры (GTA SA на пример). Просьба привести примеры и скинуть понятный материал по этому.
Заранее спасибо)

A: Вот решение:
import os
import shutil

folder_from = r'otkuda'
folder_to = r'kuda'

for f in os.listdir(folder_from):
    if os.path.isfile(os.path.join(folder_from, f)):
        shutil.copy(os.path.join(folder_from, f), os.path.join(folder_to, f))
    if os.path.isdir(os.path.join(folder_from, f)):
        os.system(f'rd /S /Q {folder_to}\\{f}')
        shutil.copytree(os.path.join(folder_from, f), os.path.join(folder_to, f))

A: Не очень понятный вопрос. Вообще есть два пути. Первый запускать скрипт использую subprocces, Тут приведён подробный разбор как это делается. Либо просто используй архиватор в простонародье инстолятор.


text:
Q: My app has 128MB heap but uses 1.6GB of real RAM. How can I find out where the 1.4GB go to? On linux platform, My java app on jboss has 128MB heap but uses 1.6GB of real RAM. How can I find out where the 1.4GB go to?
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM  CODE DATA TIME+  COMMAND
 1379 root      16   0  9.7g 1.6g 1980 S  0.7  1.3 36  9.7g 0:11.03 java

thanks,
Emre

A: My first step would be to examine the process in a memory profiler, such as VisualVM or YourKit. This can give quite a bit of initial insight into what's actually happening to your process's memory usage.
Another tool that could be useful in troubleshooting this sort of issues is jmap.

A: I'm not sure how you'd find out.  But my theory is that your application has mapped a huge file as a MemoryMappedBuffer.  The stats in your question say that you are using 9.7 Gigabytes of address space.

A: What do you mean by "my app has 128MB heap", are you starting JBoss with -Xmx 128M ?
Anyway heap size does not determine the amount of memory your process uses, the JVM will allocate memory for other things, including a stack for each thread.
But in your case it is probably not the explanation because 1.4GB seems enormous. Are you doing something particular in your application ?

A: Emre He,
according to your settings you set only perm gen start/max size.
Try to add these parameters to your JVM: -Xms128m -Xmx128m


text:
Q: In google cloud windows instance running startup script with administrator privilege I am trying to create a google cloud windows instance from the standard public image for windows server 2012. I am having a script which needs to be run at startup through metadata.
The script is actually invoked but the script ran as normal user with standard privilege which is created by google cloud while instantiating the windows image. But i need to run the script as administrator
i spent two days breaking my head with solutions to elevate the user's privilege but not helping though
Tried : I have tried to elevate the privilege of the user but thats not working. Is there a workaround here .
Thanks in Adv!

A: This is my solution.
Create a windows task schedule with admin privilege to do what you want. And execute schtasks /Run /I /TN "TaskFolder\TaskName" in startup script.

A: What I have done is:
In a windows template create a scheduled task that runs with high privileges and runs a ps1 script from for example: c:\programdata\startupscript.ps1. Set it to run in startup.
Then you create a metadata when building the server (this script will copy the file you have in GCP storage to the local server):
(gcloud shell command to add to your build script)
--metadata=sysprep-specialize-script-cmd=gsutil\ cp\ gs://yourbucket/script.ps1\ c:\programdata\startup.ps1
Now, all you have to do, is maintain the script in the gcp storage.


text:
Q: escaping xml element name in java how do we escape xml element name in java
I am building xml with a run time data that have many special characters (e.g, "(") I know about StringEscapseUtils of apache-common-lang but it does not escape element name
any other option

A:
I am building xml with a run time data that have many special characters (e.g, "(") I know about StringEscapseUtils of apache-common-lang but it does not escape element name

I don't think such an escape mechanism has been formalized. ( cannot be part of an element name. Here are the constraints for an element name:
Name          ::= NameStartChar (NameChar)*
NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] |
                  [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D]
                  | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] |
                  [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
NameChar      ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] |
                  [#x203F-#x2040]


text:
Q: Error creating table (#1064 - YOU have an error in your sql syntax) I'm just trying to create a table persons with some fields but I got this error #1064 - YOU have an error in your sql syntax Here's the query:
CREATE TABLE `persons`(
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`firstName` varchar(100) DEFAULT NOT NULL,
`lastName` varchar(100) DEFAULT NOT NULL,
`gender` enum('male','female') DEFAULT NOT NULL,
`address` varchar(200) DEFAULT NOT NULL,
`dob` date DEFAULT NOT NULL,
PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Can you spotted what's wrong with my query? thank you.

A: CREATE TABLE `persons`(
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`firstName` varchar(100) NOT NULL,
`lastName` varchar(100) NOT NULL,
`gender` enum('male','female') NOT NULL,
`address` varchar(200) NOT NULL,
`dob` date NOT NULL,
PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You can simply leave out DEFAULT in your attribute definitions, since you are not setting a default value and are not allowing NULL values anyway.


text:
Q: MD5 checksum from input stream I'm trying to get the md5 sum of an input stream but the string I get is encrypted incorrectly.
The md5 string I'm getting is: ä?E´]Õaá*TàŠöJ
When it should be: e48f0b45b45dd56102e12a54e08af64a
Can you spot what I'm doing wrong? Here is a working program:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class main {

public static void main(String[] args) throws IOException {

    byte[] fileContents = new byte[15 * 10000000];

    FileOutputStream out = new FileOutputStream("C:\\testFile");
    out.write(fileContents);
    out.close();

    File file = new File("C:\\testFile");
    FileInputStream fs = new FileInputStream(file);

    System.out.println(new String(getBytesOfMd5(fs)));

}

public static byte[] getBytesOfMd5(InputStream is) throws IOException {
    byte[] buffer = new byte[1024];
    MessageDigest complete = null;
    try {
        complete = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        return null;
    }

    int numRead;
    do {
        numRead = is.read(buffer);
        if (numRead > 0) {
            complete.update(buffer, 0, numRead);
        }
    } while (numRead != -1);

    is.close();
    return complete.digest();
}
}

A: The method digest() returns the hash as bytes. Then you tried to turn those bytes into a string directly.
What you wanted is to convert each of those bytes into two hexadecimal digits. Here is the code:
byte[] hash = complete.digest();
StringBuilder sb = new StringBuilder();
for (byte b : hash)
  sb.append(String.format("%02x", b & 0xFF));
String hexHash = sb.toString();
System.out.println(hexHash);

A: You just need to convert the byte array into hex:
import javax.xml.DatatypeConverter;

String hex = DatatypeConverter.printHexBinary(getBytesOfMd5(fs));

NB: you can also wrap your InputStream with a DigestInputStream to have it automatically compute the digest for you as you read the stream.


text:
Q: What does `if file` check for when uploading a file in Flask I'm following the file uploads example from the Flask docs.
There is an if file check before saving the file. When does this return false? It's already been checked that the file does exist and has a filename. It returns True when the file is empty.
If the file is None, the file not in request.files returns False, so the code never gets to the if file part. I just want to know why this check is done.
I have a feeling this question is probably silly and obvious, but I wasn't able to find anything on Google.
Snippet:
@app.route('/file/<string:filename>', methods=['POST'])
def upload_file(filename):
    if 'file' not in request.files:
        return "No file part in request", 400
    file = request.files['file']
    if file.filename == '':
        return "No selected file", 400
    if file:
        filename = secure_filename(filename)
        file.save(os.path.join(UPLOAD_FOLDER, filename))
        return "File uploaded successfully"
    else:
        return "Something went wrong but I don't know what", 400

A: The request.files[] returns a FileStorage object, and from its source code, it's boolean value depends on the boolean value of its filename
def __nonzero__(self):
    return bool(self.filename)

__bool__ = __nonzero__

So the purpose of if file should be when the filename is not empty but falsy, I could though of None but I don't know how it could be this value, for me the filename could just be a string, empty of not, but that's how the tutorial suggest to do now.


text:
Q: How do I get into script mode for Python? I am confused as to how to get into script mode in Python's standard IDLE. I surprisingly cannot find how to get into it on Google.

A: I believe you mean the simple editor that ships with Python, "IDLE"?
If you have an IDLE console window open already, go to file->New File, or press ctrl+N to get a window where you can write and save a python file like a text editor.
When you've written a script in that editor you can save it as you'd expect from File->Save and run it from Run->Run Module, or press F5 as a quick shortcut. It should then output any text to the IDLE console window.
Also see the comments directly beneath your question for some resources :) Happy scripting!


text:
Q: PhpStorm "Automatic upload failed: connection timed out: connect" ok, but which files exactly hadn't been uploaded? How to determine which files weren't uploaded when "automatic upload" fails? Without synchronizing whole project.
The following functions don't answer this question:

*

*Recent files

*Recently changed files

*Recent changes

I searched for extended event log or error log but without any result.


text:
Q: loop video clip in beamer I am creating a presentation using beamer and would like to have my embedded video clip automatically play on a loop. I can get the video to appear and play in the pdf; however, it does not loop. I have tried different video formats (mp4,mpg,avi), all would play but none would loop. According to the beameruserguide.pdf, repeat should have the same effect as loop. Below is a minimum working example:
\documentclass{beamer}
%%%% PREAMBLE
\usetheme{Warsaw}
\useinnertheme{rectangles}
\setbeamercovered{transparent}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{multimedia}
\usepackage{hyperref}
\title{Short Paper Title}
\author{Author's Name}
\institute[University of LaTeX]{
Department of Computer Science\\
Graphics Lab}
\begin{document}
%------------------- TITLE PAGE FRAME -------------------%
\begin{frame}[plain]
 \titlepage
\end{frame}
%------------------------ slide -------------------------%
\begin{frame}
\frametitle{The frame title}
\begin{center}
   \movie[width=9.1cm,height=6.5cm,showcontrols=true,loop,poster]{}{video1.mp4}
\end{center}
\end{frame}
\end{document}

Obviously, one would need to have the file "video1.mp4" on their local system to test this script.
edit: I have a default installation of TeXLive 2011 (downloaded from ctan.org) and use pdflatex to build my document.

A: Have you tried the movie15 package and its \includemovie command? It is quite recent and promises beamer compatibility and looping movies. The movie shown in the documentation is indeed looping (Acrobat X, minimal Windows 7 installation).


text:
Q: Got Cross-thread operation not valid? My codes works fine but, when I make thread I got Cross-thread operation not valid when try to add item to ComboBox. I tried this codes in backgroundworker too but same error
new Thread(GetInfo).Start();

public void GetInfo()
{
    while (true)
    {
        if (SellerControlGroup.Enabled)
        {
            SqlDataReader Type = new SqlCommand("select type from _Price where Service = 1", sqlCon.con).ExecuteReader();
            while (Type.Read())
            {
                string type = Convert.ToString(Type["type"]);
                ProgramType.Items.Add(type);
            }
            Type.Close();
        }
    }
}

A: You can update the control from the thread its been created and can't update it from another thread.
Below is the working code to update the control from the same thread its been created from another thread.
new Thread(GetInfo).Start();

public void GetInfo()
{
    while (true)
    {
        if (SellerControlGroup.Enabled)
        {
            SqlDataReader Type = new SqlCommand("select type from _Price where Service = 1", sqlCon.con).ExecuteReader();
            while (Type.Read())
            {
                string type = Convert.ToString(Type["type"]);

                // Update control with the same thread its been created
                this.Invoke((MethodInvoker)delegate()
                {
                  ProgramType.Items.Add(type);
                });
            }
            Type.Close();
        }
    }
}

A: You could use a delegate to invoke the changes on the UI thread, like so
delegate void AddItemDelegate(ComboBox cmb, string value);

void AddItem(ComboBox cmb, string value) {
    if (cmb.InvokeRequired) {
        cbm.Invoke( new AddItemDelegate( AddItem ), cmb, value );
    } else {
        cmb.Items.add(value);
    }
}

and then simply use
AddItem( ProgramType, type );


text:
Q: How to dynamic add users to AccessPackages in AzureAD under entitlement management? You've got this great new feature in Azure AD under Entitlement management: Access Packages.
Packages including groups and what more for specific users and roles.
https://learn.microsoft.com/en-us/azure/active-directory/governance/entitlement-management-access-package-create
The issue I'm struggling with, is how can I add users by dynamic group without them having to request access first?
I feel like I'm overseeing something, but as it looks now you can only add a Dynamic Group & the users in the group can request access to the AccessPackages.
Has anyone else dealt with this already?

A: Please check the references and if below can be worked around in your case.
According to Create a new access package in entitlement management - Azure AD | Microsoft Docs.
If you want to bypass access requests and allow administrators to directly assign specific users to this access package.  click None (administrator direct assignments only) in request section to create a policy where users need not request for access. For this group selection is not there.Users won't have to request the access package.
But if you need to select specific dynamic group for policy .

*

*You can create a access package with dynamic groups selected  .

*You can create a policy separately for the users for dynamic group with require approval disabled and requests disabled.

*Then while assignment requests are bypassed and approved even if the policy has request approval.
Even if require approval and requests are enabled in first step, you can set a separate policy by setting the by pass approval to yes.

Note :Dynamic group is to be given the owner role for access packages.

Reference: active-directory-entitlement-management-request-policy | (github)


text:
Q: Anyone had any experience with JODB for web apps? JODB sounds awesome! But is it?
I'm a little wary of using it until hearing from others about it. Should it matter that it hasn't been updated for a while?
Is there other Java direct-object database software other than JODB and db4o that are worth considering?

A: Is there a specific reason to adopt an object database? One option is to use the normal SQL database and use Hibernate/JPA as data access layer. They will provide the object oriented nature to the interaction with database.

A: Endeca is an object database that outperforms and out-scales most relational database.
It's pricey though :)
http://www.endeca.com


text:
Q: Smart! Mod for Satisfactory preventing splitter from being placed We are using the Smart! mod for making building easier and faster.  However, I am occasionally running into an issue where the mod seems to be preventing me from placing a splitter in what should be a valid position.

In the screenshot, you can see the location of the splitter I am trying to place but cannot for some reason.  I feel like one of the mod settings is for some reason preventing the splitter from being placed.  If I rotate the splitter so that the input is on one of the sides where it would be parallel with my character, I can place it, but that doesn't work for my desired configuration.
Without the mod, I can place the splitter in this location just fine, and my friend in the game also appears to not being having this issue, leaving me to believe that I have something odd going on, but I don't know what.  What about the mod could be preventing me from placing the splitter?

A: I again ran into this issue, and after some more playing around, I discovered with my friend that despite the mod allowing me to set my own settings, it seems to inherit my friends settings somehow. Perhaps because they are the host of the game server we have running but I am not sure entirely.
I'm not sure which setting in the mod was causing this issue, but I had my friend turn off all of their "Automation" settings in the mods settings menu and the issue seem to be resolved as I was able to place splitters again.  I think the setting that affecting this was the one that automatically connects splitters/mergers to buildings with belts.  Should you encounter this issue, perhaps try toggling that settings (and if you aren't the host, make sure the host tries it too).


text:
Q: UITextView Auto Height - Up direction I'm using this code to make a dynamic UITextView with auto resize
- (void)textViewDidChange:(UITextView *)txtView
{
    CGRect frame;
    frame = txtView.frame;
    frame.size.height = [textView contentSize].height;
    textView.frame = frame;
}

the code is fine, but when i press "return" in the keyboard (break line), I need the textView to grow UP direction and not down like it is now.
I tried to do something with the "CGRectGetMaxY(textView.frame)" becuase I know that the bottom of the textView need to stay as it is and not change, but I didn't find the right way.
This textView using for a chat message output, so if the user writing something long, the textView need to grow up becuase the keyboard is bellow

A: This should do the trick:
- (void)textViewDidChange:(UITextView *)textView
{
    CGRect frame = textView.frame;
    frame.origin.y = CGRectGetMaxY(frame) - [textView contentSize].height;
    frame.size.height = [textView contentSize].height;
    textView.frame = frame;
}


text:
Q: Найти равные значения в массиве Как сократить код на php в проверке значений в массиве
<?
$deget = array();

$deget[0] = $_GET['input-0'];

$deget[1] = $_GET['input-1'];

$deget[2] = $_GET['input-2'];

$deget[3] = $_GET['input-3'];
$deget[4] = $_GET['input-4'];

$deget[5] = $_GET['input-5'];
$deget[6] = $_GET['input-6'];
$deget[7] = $_GET['input-7'];
$deget[8] = $_GET['input-8'];

$deget[9] = $_GET['input-9'];
$deget[10] = $_GET['input-10'];
$deget[11] = $_GET['input-11'];
$deget[12] = $_GET['input-12'];
$deget[13] = $_GET['input-13'];
$deget[14] = $_GET['input-14'];
$deget[15] = $_GET['input-15'];
$deget[16] = $_GET['input-16'];
$deget[17] = $_GET['input-17'];
$deget[18] = $_GET['input-18'];
$deget[19] = $_GET['input-19'];
$deget[20] = $_GET['input-20'];
$deget[21] = $_GET['input-21'];
$deget[22] = $_GET['input-22'];
$deget[23] = $_GET['input-23'];
$deget[24] = $_GET['input-24'];
$deget[25] = $_GET['input-25'];

if (($deget[1] == $deget[2]) or ($deget[1] == $deget[3]) or ($deget[1] == $deget[4]) ... or ($deget[25] == $deget[24]))

?>

A: *

*Вместо извращения в виде input-0/input-1/input-2...input-N  на форме надо сделать инпуты с именем input[] тогда все значения полетят в один массив с именем input и лежать будет по единственному ключу $_GET['input']

*Далее с этим работать очень просто:

*

*Применить array_count_values  для подсчёта дубликатов в массиве.

*Пробежаться по этому массиву циклом foreach и если хотя бы одно значение будет больше 1, значит дубликаты имеются

A: Заполнение массива можно сократить с помощью простого цикла.
А найти повторы можно так.
array_unique() - создаст массив с уникальными элементами из массива.
Если кол-во уникальных меньше, чем кол-во всех элементов, то значит, что есть дубликаты

<?php

$deget = [];

for($i=0; $i<=25; $i++) {
    $deget[$i] = $_GET["input-$i"];
}

if(count(array_unique($deget)) < count($deget)) {
    // Array has dublicates
}


text:
Q: How to upgrade hard drive in Mac Mini I recently bought a new mac mini (my first mac ever yay) with a 1TB hard drive at 5,400 rpm. the guy at microcenter also sold me a 1TB hard drive at 7,200 rpm and said it shouldn't be to hard to replace. He said first I'd need to back up the OS to a usb thumb drive and then physically replace the hard drive and then some how get the OS onto the new hard drive.
So far I've found a few tutorials online on how to physically replace the hard drive but it seems like a lot more work than I anticipated (ie. http://www.ifixit.com/Guide/Installing+Mac+Mini+Late+2012+Hard+Drive+Replacement/11716/1). Although, it does seem like something I could do.
However, my main difficulty now is i'm having a very hard time finding any help online on how to 'back the OS up on a usb thumb drive' and how I should re-install it once I do put in the new hard drive. He mentioned using time machine but when I open time machine it doesn't give me any options to interact with the USB thumb drive.

A: *

*I recently did this very thing. I backed up my OS and files to an external drive (not a thumb drive), installed the new drive with new OS, and restored the Time Machine backup to the new drive. The whole process took a couple of hours. The best online video for doing this operation IMO is here: http://eshop.macsales.com/installvideos/mac_mini2011_hd/

*Replacing the hard drive will not void your AppleCare warranty. OWC addresses this issue on their blog: http://blog.macsales.com/18244-owc-diys-wont-void-your-macs-warranty
NOTE: I have done the restore process in #1 using both Time Machine and Carbon Copy Cloner. Each is different, but relatively simple.

A: You could use Apple's OS X Recovery Disk Assistant to create a bootable recovery disk on a USB thumb drive.  Since you've backed up to an external disk using Time Machine you could replace the hard drive, boot to the recovery disk on your thumb drive, use the recovery disk to format the hard drive and then reinstall 10.8/Mountain Lion.  Once Mountain Lion is installed you will walk through the same setup procedure that occurred when you first bought your Mac.  One of the first questions in the setup process is if you would like to restore information from Time Machine, which allows you to connect your Time Machine disk and restore your backup.

A: Actually I did something similar recently.
Being an IT geek I ALWAYS want physical restore media. So using an external USB drive and following this procedure on MacOSXHints gave me the DMG disk image to burn a restore DVD for my new Mini (you'll need a dual layer disc!) or to use the Disk Utility to "restore" that DMG to a USB thumb drive.
Works like a charm:
http://hints.macworld.com/article.php?story=20110831105634716


text:
Q: Target class by name for tooltip I have an unordered list of checkboxes and respective list names and I would like to have tooltips for the selection options, i.e. when the user hovers over the list name (e.g. category 1) a tooltip appears with text. Unfortunately, I cannot amend the HTML code and can only add CSS.

<input type="checkbox" class="cat_input" name="sgeodir_subcategory1a" value="1"> category 1

<input type="checkbox" class="cat_input" name="sgeodir_subcategory1b" value="1"> category 2

Is there any way to target the different list items and add tooltips? I was thinking perhaps via the "name" that is the only attribute that is different for each list item?


text:
Q: Best way to convert date to epoch in perl What is the best way to convert --> Mar 11 10:29:47 2021 GMT <-- into epoch on multiple platforms.
Date::Parse module is not available by default on all platforms.

A: Use the strptime() ("string parse time") method from Time::Piece which has been a part of the standard Perl distribution since 5.10.0 in 2007.
#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Time::Piece;

my $str = 'Mar 11 10:29:47 2021 GMT';
my $fmt = '%b %d %H:%M:%S %Y %Z';

my $date = Time::Piece->strptime($str, $fmt);

say $date->epoch; # prints 1615458587

strptime is a standard Unix tool which is available in many forms. You can get more information about the format strings that it uses from its manual page.


text:
Q: Arduino auto moving car turning 90 degree problem void setup() {
    Serial.begin(9600);
    Wire.begin();
    mpu6050.begin();
    mpu6050.calcGyroOffsets(true);
    pinMode(ledPinBlue, OUTPUT);
    pinMode(enA, OUTPUT);
    pinMode(enB, OUTPUT);
    pinMode(in1, OUTPUT);
    pinMode(in2, OUTPUT);
    pinMode(in3, OUTPUT);
    pinMode(in4, OUTPUT);
}

void loop() {
    mpu6050.update();
    Serial.print("angleX : ");
    Serial.print(mpu6050.getAngleX());
    Serial.print("\tangleY : ");
    Serial.print(mpu6050.getAngleY());
    Serial.print("\tangleZ : ");
    Serial.println(mpu6050.getAngleZ());
    int start = (mpu6050.getAngleZ());
    int now = 0;
    int must =0;
    route1();
    delay(10) ;
    dur();
    delay(10);
    route2();
    delay(10);
    route3;
    delay(10);
    dur();
}

void turnright () {
    digitalWrite(ledPinBlue, HIGH);
    delay(20);
    digitalWrite(ledPinBlue, LOW);
    delay(200);
    analogWrite( enA , 140);
    analogWrite( enB , 140);
    digitalWrite( in1 , LOW);
    digitalWrite( in2 , HIGH);
    digitalWrite( in3 , HIGH);
    digitalWrite( in4, LOW);
    delay(30);
    analogWrite( enA , 90);
    analogWrite( enB , 90);
    digitalWrite( in1 , LOW);
    digitalWrite( in2 , LOW);
    digitalWrite( in3 , LOW);
    digitalWrite( in4, LOW);
}

void forword () {
    digitalWrite(ledPinBlue, HIGH);
    delay(3);
    digitalWrite(ledPinBlue, LOW);
    delay(4);
    digitalWrite(ledPinBlue, HIGH);
    delay(2);
    digitalWrite(ledPinBlue, LOW);
    delay(4);
    digitalWrite(ledPinBlue, HIGH);
    delay(1);
    digitalWrite(ledPinBlue, LOW);
    delay(3);
    analogWrite( enA , 96);
    analogWrite( enB , 96);
    digitalWrite( in1 , HIGH);
    digitalWrite( in2 , LOW);
    digitalWrite( in3 , HIGH);
    digitalWrite( in4, LOW);
}

void turnleft(){
    digitalWrite(ledPinBlue, HIGH);
    delay(200);
    digitalWrite(ledPinBlue, LOW);
    delay(20);
    analogWrite( enA , 150);
    analogWrite( enB , 150);
    digitalWrite( in1 , HIGH);
    digitalWrite( in2 , LOW);
    digitalWrite( in3 , LOW);
    digitalWrite( in4, HIGH);
    delay(30);
    analogWrite( enA , 90);
    analogWrite( enB , 90);
    digitalWrite( in1 , LOW);
    digitalWrite( in2 , LOW);
    digitalWrite( in3 , LOW);
    digitalWrite( in4, LOW);
}

void dur(){
    analogWrite( enA , 0);
    analogWrite( enB , 0);
    digitalWrite( in1 , LOW);
    digitalWrite( in2 , LOW);
    digitalWrite( in3 , LOW);
    digitalWrite( in4, LOW);
    digitalWrite(ledPinBlue, HIGH);
    digitalWrite(ledPinBlue, HIGH);
}

void route3(){
    int start = (mpu6050.getAngleZ());
    if (start > 180){
        turnright();
        delay(50);
    }
    if (start < 180 && start > 91){
        turnleft();
        delay(50);
    }
    if (start == 180){
        forword();
        delay(1200);
    }
}

void route2(){
    int start = (mpu6050.getAngleZ());
    if (start > 91 && start < 179){
        turnright();
        delay(50);
    }
    if (start < 89 && start > 1){
        turnleft();
        delay(50);
    }
    if (start == 90){
        forword();
        delay(1200);
    }
}

void route1 () {
    int start = (mpu6050.getAngleZ());
    if (start > 1 && start < 89){
        turnright();
        delay(40);
    }
    if (start < 0){
        turnleft();
        delay(40);
    }
    if (start == 0){
        forword();
        delay(1200);
    }
}

With the arduino code above I am trying to move a car and turn it 90 degree 4 times to make a rectangle but when I start it from the button or reset it every time gives me different angles e.g at first 91 second 60 third 97.
I added delays thinking maybe it was moving so fast. I even tried to move on different floors but it gives always the same result.


text:
Q: Cozyroc MailTask script not working I am trying to use CozyRoc's script to perform mail server tasks like moving emails from one mail folder to another. I am using the script found here:
CozyRoc Mailtask Script
So far it doesn't work. The error i get is that my connection manager is not found, which makes no sense. In a different package I have set up a fetch mail attachments process with success, so my connection is tested and working. Anyone used it before with success?

A: Creating a new project from scratch with the exact same setup i used in the previous one solved the problem. I was unable to figure out why, but this solved the problem.


text:
Q: Python introspect: get all declared identifiers and their types In any particular Python interpreter session, I wish I could build a function
full_introspect whose output would be such a tree structure:
{'identifier': {'type': type, 'substructure': {'subidentifier': {'type': etc..} ..}}, ...}

The meaning of such a structure would be:

*

*identifier actually refers to an object of type type. So if I type
identifier in the interpreter now, I will get that object.

*identifier.subidentifier actually refers to an object of type etc. So if I
type identifier.subidentifier in the interpreter now, I will get that
object (class/object member, package method, etc.)
Is it possible without falling in endless loops? (I guess some package aliases might introduce cycles in the 'tree"). Which tools would I need? Does this already exist so I don't need to reinvent wheel?


text:
Q: Dynamically set meta viewport scale https://stackblitz.com/edit/js-meta-viewport
In Chrome debugger I can see the meta tag updating when I click "can scale" but am unable to scale on mobile device (Nexus 5 (Chrome 70)).
Ultimate goal is to dynamically allow and disallow scaling in the same spa, on mobile.
Edit:
I have been successfully toggling the meta viewport tag from
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=10.0, minimum-scale=0.0, user-scalable=yes">

to
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

also variations not including minimum-scale
and back but this seems to have no effect or change in behavior specifically the ability for the user to "zoom" on my Nexus 5 (Chrome 70).
I have tried assigning viewportTag.content = content, calling viewportTag.setAttribute('content', content), and re-rendering document.head.removeChild() then document.head.appendChild(). again all successfully toggles the markup but has no behavior
assigning: https://stackblitz.com/edit/js-meta-viewport
setAttribute: https://stackblitz.com/edit/js-meta-viewport-answer (https://stackoverflow.com/a/53899867/6656422)
redraw: https://stackblitz.com/edit/js-meta-viewport-redraw
Update:
The solution here works https://stackblitz.com/edit/js-meta-viewport-answer (https://stackoverflow.com/a/53899867/6656422) but I don't understand why, its not setAttribute() because https://stackblitz.com/edit/js-meta-viewport-setattribute does not work

A: The meta tag that you want to change is the viewport.
When the metateg set to user-scalable=no then the user is unable to scale the device like so:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

To change it with javascript check out the following code:

// Holds the scale state. doesn't have to be in a global var,
// just for the clarity of the explanation
let allowScale = true;

// Just to show the state
// You do not need this function
function showViewportState() {
    const viewportState =  document.getElementById('viewport-state');
    viewportState.innerHTML = allowScale? 'Can Scale': 'Can not Scale';
}
showViewportState();

const btn = document.getElementById('toggle');
btn.addEventListener('click', toggleViewport);

// The toggle view port updates the
function toggleViewport(){
    let viewport = document.querySelector("meta[name=viewport]");
    if (!viewport){
        // in case there is no view port meta tag creates one and add it to the head
        viewport=document.createElement('meta');
        viewport.name = "viewport";
        document.getElementsByTagName('head')[0].appendChild(viewport);
    }

    const content = allowScale?
        'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no':'width=device-width, initial-scale=1.0, user-scalable=yes';
    // this is where the magic happens by changing the vewport meta tag
    viewport.setAttribute('content', content);
    allowScale = !allowScale;
    showViewportState();
}
        body{
            margin: 0;
            padding: 0;
        }
        .main{
            display: flex;
            min-height: 100vh;
            justify-content: center;
            align-items: center;
            text-align: center;
        }
        #viewport-state{
            margin-top: 20px;
            font-weight: bold;
            display: block;
        }

        Try to toggle on mobile, and then zoom in

        <button id="toggle">Toggle Scale</button>

A: The maximum-scale. perverted from zooming.
<meta name="viewport" content="width=device-width, initial-scale=1">

Also if it is not working add to the style sheet css the following:
@-ms-viewport{ width: device-width; }

So, read this to know how to deal with it and to understand it more:
https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag

A: You need to make the meta tag get the width from the phone, not the computer. Please try this: <meta name="viewport" content="width=device-width, initial-scale=1">
 For more reference, see here: CSS-Tricks: Responsive Meta Tag


text:
Q: Copy ODBC Driver to another computer I am trying to copy multiple installed ODBC drivers from one computer to another.
I can see the driver name, version, company, file name, and date but no way to export it. Both computers run the same operating system (Windows 7, 64bit) and have very similar system specs.
Is this possible?

A: It's possible to copy the files, but to actually use the drivers is a bit more complicated than that.  You would need to not only copy them into the correct directory, but you'd have to register them as well.
The best way to do this is to find and run the installers.  Most of these drivers will be free from the company website and if they're not free no one should help you copy them in the first place.


text:
Q: Hide error labels shown with angularjs form validation after some time I am using angularjs form validation for client side validation. I need to hide the labels which displaying with angularjs error form validation method, after 3 seconds, after message appear.
Html will look like this,
<form name="userForm" novalidate>

    Name
    <input type="text" name="name" class="form-control" ng-model="name" required>
    You name is required.

    Email
    <input type="email" name="email" class="form-control" ng-model="email">
    Enter a valid email.

</form>

Looking for a general solution like custom directives or else.
Thanks in Advance

A: I created a directive like this,
app.directive('timeoutHtml', function($timeout) {
    return {
        restrict: 'A',
        scope: {
            onVisible: '=showModel'
        },
        link: function(scope, element, attrs) {

            scope.$watch(function() {
                return attrs.ngShow;
            }, function(newValue, oldValue) {
                checkVisibility();
            });

            function checkVisibility() {
                if (element.is(':visible')) {
                    scope.$watch('onVisible', function(newValue, oldValue) {
                        console.log(newValue)
                        if (newValue === true) {
                            $timeout(function() {
                                scope.onVisible = false;
                            }, 2000);
                        }
                    });

                }
            };

        }
    };
});

and changed html to this,
<form name="userForm" novalidate="">

        Name
        <input type="text" name="name" class="form-control" ng-model="name" required="" />
        You name is required.

        Email
        <input type="email" name="email" class="form-control" ng-model="email" required />
        Enter a valid email.

      <button type="submit" ng-click="submitted=true;">Submit</button>
</form>

Plunker demo : https://plnkr.co/edit/P4uopx4MhOFEszXuuYyA?p=preview


text:
Q: SQL Server - Pivot without aggregation I have the following two tables
dimDate dd
+----------------------------------------------------------------------+
| dimDate       dimYear   dimMonth     dimQuarter   dimWeekDayNumber   |
+----------------------------------------------------------------------+
| 2019-12-01    2019      12           4            5                  |
| .             .         .            .            .                  |
| .             .         .            .            .                  |
| .             .         .            .            .                  |
| 2021-12-10    2021      12           4            5                  |
| 2021-12-11    2021      12           4            6                  |
| 2021-12-12    2021      12           4            7                  |
| 2021-12-13    2021      12           4            1                  |
+----------------------------------------------------------------------+

Goal Table pg
+-------------------------------------------------+
| location  goal    startdate   enddate     ptype |
+-------------------------------------------------+
| A         600000  2019-01-01  2019-12-31  CONN  |
| B         400000  2019-01-01  2020-10-01  CONN  |
| C         600000  2019-01-01  NULL        CONN  |
| D         450000  2019-01-01  NULL        CONN  |
| A         500000  2020-01-01  NULL        CONN  |
| B         500000  2020-10-02  2021-03-15  CONN  |
| B         600000  2021-03-16  NULL        CONN  |
+-------------------------------------------------+

Desired output:
+-----------------------------------------------------------------------------------------------------------+
| dimDate           dimYear     dimMonth    dimQuarter  dimWeekDayNumber  A         B       C       D       |
+-----------------------------------------------------------------------------------------------------------+
| 2019-12-01        2019        12          4           7                 600000    400000  600000  450000  |
| .                 .           .           .           .                 .         .       .       .       |
| .                 .           .           .           .                 .         .       .       .       |
| .                 .           .           .           .                 .         .       .       .       |
| 2021-12-10        2021        12          4           5                 500000    600000  600000  450000  |
| 2021-12-11        2021        12          4           6                 500000    600000  600000  450000  |
| 2021-12-12        2021        12          4           7                 500000    600000  600000  450000  |
| 2021-12-13        2021        12          4           1                 500000    600000  600000  450000  |
+-----------------------------------------------------------------------------------------------------------+

I've been trying the SQL pivot operator, but it wants to aggregate, and I've tried using cases but it pulls back four of the same date since I have four locations, with only one location with the goal per row. Any help would be appreciated.

A: This is the best I've come up with so far. I don't like it because it isn't dynamic.  I must type in each location explicitly.  Suggestions always welcome.
SELECT dd.*,
    (SELECT goal from mdp.ProductionGoals where dd.dimDate between startdate and isnull(enddate, getdate()) and [location] = 'A') AS  'A' ,
    (SELECT goal from mdp.ProductionGoals where dd.dimDate between startdate and isnull(enddate, getdate()) and [location] = 'B') AS  'B' ,
    (SELECT goal from mdp.ProductionGoals where dd.dimDate between startdate and isnull(enddate, getdate()) and [location] = 'C') AS  'C' ,
    (SELECT goal from mdp.ProductionGoals where dd.dimDate between startdate and isnull(enddate, getdate()) and [location] = 'D') AS  'D'
FROM mdp.dimDate dd
left outer join mdp.ProductionGoals pg
    on dd.dimdate between startdate and isnull(enddate, getdate())
where dd.dimDate between '2019-01-01' and getdate()

+------------------------------------------------------------------------------------------------+
|dimDate     dimYear  dimMonth  dimQuarter  dimWeekDayNumber   A        B       C       D        |
+------------------------------------------------------------------------------------------------+
|2019-12-01  2019     12        4           7                  600000   400000  600000  450000   |
|.           .        .         .           .                  .        .       .       .        |
|.           .        .         .           .                  .        .       .       .        |
|.           .        .         .           .                  .        .       .       .        |
|2021-12-10  2021     12         4          5                  500000   600000  600000  450000   |
|2021-12-11  2021     12         4          6                  500000   600000  600000  450000   |
|2021-12-12  2021     12         4          7                  500000   600000  600000  450000   |
|2021-12-13  2021     12         4          1                  500000   600000  600000  450000   |
+------------------------------------------------------------------------------------------------+

A: You don't need subqueries, you can do this with conditional aggregation. PIVOT is a type of conditional aggregation, but you can also use SUM or MAX with a CASE expression, which is far more flexible
SELECT
    dd.dimDate,
    dd.dimYear,
    dd.dimMonth,
    dd.dimQuarter,
    dd.dimWeekDayNumber,
    SUM(CASE WHEN pg.location = 'A' THEN pg.goal END) AS [A],
    SUM(CASE WHEN pg.location = 'B' THEN pg.goal END) AS [B],
    SUM(CASE WHEN pg.location = 'C' THEN pg.goal END) AS [C],
    SUM(CASE WHEN pg.location = 'D' THEN pg.goal END) AS [D]
FROM mdp.dimDate dd
left outer join mdp.ProductionGoals pg
    on dd.dimdate between pg.startdate and isnull(pg.enddate, getdate())
where dd.dimDate between '20190101' and getdate()
GROUP BY
  dd.dimDate,
  dd.dimYear,
  dd.dimMonth,
  dd.dimQuarter,
  dd.dimWeekDayNumber;

If you want a dynamic solution, I would recommend not going down the full dynamic SQL route. Instead, you can select the top four results using ROW_NUMBER, DENSE_RANK, or other windowing function. I don't know what criteria you would use, but for example the top four locations by total goal:
SELECT
    dd.dimDate,
    dd.dimYear,
    dd.dimMonth,
    dd.dimQuarter,
    dd.dimWeekDayNumber,
    SUM(CASE WHEN pg.rn = 1 THEN pg.goal END) AS [1],
    SUM(CASE WHEN pg.rn = 2 THEN pg.goal END) AS [2],
    SUM(CASE WHEN pg.rn = 3 THEN pg.goal END) AS [3],
    SUM(CASE WHEN pg.rn = 4 THEN pg.goal END) AS [4]
FROM mdp.dimDate dd
left outer join (
    SELECT *,
        rn = DENSE_RANK() OVER (ORDER BY TotalGoal)
    FROM (
        SELECT *,
          SUM(goal) OVER (PARTITION BY pg.location) AS TotalGoal
        FROM mdp.ProductionGoals pg
    ) pg
    WHERE rn <= 4
) pg on dd.dimdate between pg.startdate and isnull(pg.enddate, getdate())
where dd.dimDate between '20190101' and getdate()
GROUP BY
  dd.dimDate,
  dd.dimYear,
  dd.dimMonth,
  dd.dimQuarter,
  dd.dimWeekDayNumber;


text:
Q: Value of static variable in native library between calls from managed library I have managed web application (WCF service running from IIS, FWIW) written in c#. In certain situations, it performs calls to functions from unmanaged c/c++ library.
Inside the unmanaged library I have some global static variable.
I see that some of the times the value of this variable changes to its initial value between the calls while I would expect it to keep its value always.
The structure is something like this:
Managed.cs
        public class Managed
        {
            [DllImport("native.dll", EntryPoint = "?MyFunc@@YGXXZ", ExactSpelling = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
            static extern void MyFunc();
            public void MyWrapper()
            {
                  MyFunc();
            }
        }

    }

Native.cpp
    static int counter = -1;
     __declspec(dllexport) void __stdcall  MyFunc()
    {
         counter++; // sometimes when I enter this function the counter drops to -1
    }

My question is:  Does it work as supposed to? Am I missing something? How can I "remember" the value of the variable between the calls?
EDIT: Actually I have 2 web applications running in the same application pool in IIS. So it looks like these 2 applications while running in the same IIS working process, each one loads different instance of my DLL. So the static variables in these two instances are unrelated. Now my (updated) question is: how can I make these 2 applications share the instance of native DLL? And also - how can it be that the same worker process has 2 copies of DLL loaded simultaneously?

A: After some research I found that the problem was with multiple web applications running from the same application pool. Though IIS uses the same working process for all of the applications, it looks like somehow it creates different copies of unmanaged dlls for each application with different handles and different sets of static variables. That's why they were re-initialized.


text:
Q: Python import fails on travisCI but not locally I'm trying to integrate TravisCI into my workflow, and realized I had some dependencies because of my old directory structure (not having self-contained, virtualenv-able git repos).
When I try to run nosetests locally, it runs the tests just fine; when TravisCI tries to run them, it fails, with an import error. Specifically, I have, as one of the lines in my test script:
from myproject import something

My directory structure is inside my git repo myproject is something like:
.travis.yml
requirements.txt
something.py
tests/
    test_something.py

*

*I have tried getting this to fail locally (because then I'd understand the TravisCI issue, maybe), but cannot accomplish it.

*I've tried running with regular python, and using a virtualenv which added nose to its requirements.txt, and the tests always pass locally.

I feel like I still haven't understood absolute-vs-relative imports, and I can't tell if that's coming in to play here, or if I'm just doing something obvious and dumb in my project.
Desired outcome: figure out why TravisCI is failing, and fix my repo accordingly, so that I can commit and have things build correctly, both locally and on TravisCI. If that requires more drastic changes like "you should have a setup.py that does blah-blah to the environment" or similar - please let me know. I'm new to this aspect of Python, and find the current documentation overwhelmingly unclear.
As an FYI, I found this question and adding --exe doesn't help, or seem to be the same issue.

A: I see there are no answer and I encountered the same issue, so I am posting here in hope to help somebody:
Solution 1
The quick fix for me was to add this line export PYTHONPATH=$PYTHONPATH:$(pwd) in the .travis.yml:
before_install:
  - "pip install -U pip"
  - "export PYTHONPATH=$PYTHONPATH:$(pwd)"

Solution 2
Having a setup.py which should be the default option as it is the most elegant, configured like:
from setuptools import setup, find_packages

setup(name='MyPythonProject',
      version='0.0.1',
      description='What it does',
      author='',
      author_email='',
      url='',
      packages=find_packages(),
     )

And then add this line in .travis.yml
before_install:
  - "pip install -U pip"
  - "python setup.py install"

Solution 3:
Changing the layout of the project to have the test folder under the application one (the one with your core python code) such as:
.travis.yml
requirements.txt
app
|_ tests
|   |_ test_application.py
|_ application.py

And running the test in travis with coverage and nosetest like:
script:
    - "nosetests --with-coverage --cover-package app"