text:
Q: IE7 causing disappearance of background image on scroll I'm having an IE7 issue with a website i'm working on - www.mini-meals.co.uk
Basically, the background image is not showing on behind the form on the 'Free Trial'
panel, and is disappearing when I scroll down on the others.
I've tried adding position:relative; on a bunch of elements but it doesn't seem to
make a difference.
Any ideas anyone? thanks.

A: Add this style to your page to see if you are experiencing an issue with hasLayout:
.panel .panel-wrapper { zoom: 1; }

If this does correct your issue than a more "standard" way of correcting the background rendering would be to set an explicit width to those same ".panel-wrapper" items.


text:
Q: How to tell when Windows and all startup programs have completed booting? My machine (Windows 7 64-bit) takes about 3-4 mins to completely boot. Is there any way which will indicate that boot is complete, some kind of sound / pop-up, either by using Windows in-built feature or by any 3rd party application?
I require when both windows and all the startup programs have finished booting
I usually sometime sit and wait in front of the machine, that time could be better utilized for a quickie.
This is how it looks, when the hard disk light stops blinking:

A: I have a free program installed that I have used for a long time, Soluto: https://www.soluto.com/
I am just a user, not connected.
It works for me.
It does a count down and allows you to select just what you want to load on boot.
It also allows you to delay starts.

A: Run this Python script on startup. It will play the startup sound once cpu usage has been below 20 percent for 5 consecutive seconds:
import subprocess
import time

# set these to whatever works for you
# sound will play when cpu load has been < IDLE_PERCENT for IDLE_TIME consecutive seconds
IDLE_TIME = 5
IDLE_PERCENT = 20

# you can execute any program you want by changing the alert function below

def get_load():
    output = subprocess.check_output('wmic cpu get loadpercentage', shell=True)
    load = output.split()[1]
    return int(load)

def alert():
    subprocess.call([
        r"c:\Program Files (x86)\Windows Media Player\wmplayer.exe",
        r"c:\Windows\Media\Windows Logon Sound.wav"])

idleSeconds = 0

while idleSeconds < IDLE_TIME:
    load = get_load()
    if load < IDLE_PERCENT:
        idleSeconds += 1
    else:
        idleSeconds = 0

    time.sleep(1)

alert()

A: There are several potentially helpful answers here, but I think there are two important points that haven't been made:

*

*No, it is not possible to programmatically determine that Windows and all startup programs have finished booting.  This is essentially the Halting Problem and no program out there will be able to answer the question "For this arbitrary program, at what point should we say it has been loaded?".

*What is the actual problem you are trying to solve?  All of the answers here attempt to find a solution to your question, but the question itself feels like it might be missing some important information. We want to solve your problem, not just answer the question.
Reading your question again and going just by what you've said, my response would be one of:

*

*Just don't worry about it and start using your computer.  Foreground tasks are prioritized and unless you've got something really unusual going on it shouldn't matter if background tasks are running.

Or:

*

*Manually watch the system a few times and figure out the maximum amount of time it takes before the system is "ready" according to whatever metrics you have.  Get a small timer program or script and add it to your system's startup.  It can display a message or play a sound when the time you've chosen has elapsed.

This might not directly answer your current question, but hopefully it is helpful.

A: You can add a sound to startup.
You can delay the startup processes and put a sound effect to be executed first. The tool  Startup Delayer does this.

A: Why not using Windows Task Scheduler and the Event ID 100 to play a custom sound when Windows is really finished?
Under Triggers select "On an event" and

*

*Log: LogMicrosoft-Windows-Diagnostics-Performance/Operational

*Source: Diagnostic-Performance

*Event ID: 100

Under Actions select "Start a program" with

*

*Program/script: "%ProgramFiles(x86)%\Windows Media Player\wmplayer.exe"

*Add arguments: "%windir%\Media\Windows Logon Sound.wav"
Event ID: 100
Decription: Windows has started up

Source Event ID 100: Windows Diagnostics-Performance

A: Windows will treat boot finished if it was 80% idle (excluding low-priority CPU and disk activity) for 10s after reaching the Desktop UI.
To see the exact boot time use xbootmgr to trace why Windows boot slowly.

A: This may not be very effective, but it's cheap.
I usually look at the hard disk activity led (you can identify it on the case by something like a database icon), until the led stabilizes and flashes infrequently, then I know i can now use the PC without much lag. The hard disk is usually the PC's bottleneck, and if it is not being used heavily, then you have room for work.
Hope that helps.

A: I've never used it myself but Windows Task Scheduler will allow you to create a task that is triggered to run "At Startup" or "At Logon". You may be able to schedule a task to run a powershell script to access the Console.Beep() method of the .NET Framework. You may even be able to turn it into a decent tune.
From Hey Scripting Guy! Blog
[console]::beep(500,300)

Change the value of the first number to alter the pitch (anything lower than 190 or higher than 8500 can't be heard), and change the value of the second number to alter the duration

Edit:
As it turns out the Console.Beep() method may not work on 64-bit systems according to the MSDN .NET documentation. Tested beeping in a PowerShell Script and it works fine.
You may also wish to check into your startup processes. You can do this by running msconfig and clicking on services. You can also use the Sysinternals tool Autoruns.

A: By windows documentation last in load order is registry currentuser/runOnce (after start-up folder) ... but what ever load order is, some of programs can take long starting-up time.
So maybe watching CPU activity in batch file can be good solution:
@echo off
setlocal ENABLEDELAYEDEXPANSION
set cpuLimit=15
set /a lowCount=0

for /l %%i in (1,1,30) do (
   for /F %%c in ('wmic cpu get loadpercentage ^| findstr "[0-9]"') do (
       echo %%i cpu-Load: %%c  ...lowCnt: !lowCount!
      if %%c gtr %cpuLimit% ( set lowCount=0
      ) else ( set /a lowCount+=1
         if !lowCount! gtr 10 (
            ECHO BEEEEEEP ... mplay32 beep.wav... or something
            exit
         )
      )
   )
   ping -n1 127.0.0.1 >NUL
)

... and BEEEPing after spoting that in last 10 cpu-load-checks, there was cpu-load below 15%.
this batch file can be started by link in start-up folder, or better in registry HKLM\Software\Microsoft\Windows\CurrentVersion\Run

A: You wrote:

«My machine (Windows 7 64-bit) takes about 3-4 mins to completely
  boot...»

A "normal" boot takes around 30 seconds including the access to the user account. There's somethings wrong and this must be fix. In order to fix it, you have to get de data. I suggest you two utilities to troubleshoot this problem:
1) Autoruns
With this one you're able to check every process, program, driver loaded during the boot process. Tka care: this is a very powerful tool and DO NOT delete items unless you know what's you're doing. But you may Uncheck (disable) some startup logon programs...
2) System Explorer
With this tool you're able to see all process started and the history of them until System Explorer is started. Also it's possible to scan all these process for security purpose (compared to a process database..)
Check this first them give us some feedback.
You may also check the services at startup with services.msc and the status of devices with devmgmt.msc (yellow triangle for defect devices,Hard disk in PIO mode instead of DMA, and so on...) in the Windows administrative tools...
Hope this help. Let us know.

A: I had been searching for something like this, and i found the answer
i will post the actual code later on probably, but here it goes
http://msdn.microsoft.com/en-us/library/aa394226%28v=vs.85%29.aspx
just save the contents of the last part as a vbs file and run it, you can poll each system event and extract its message being displayed, simple.
what one has to do to find the boot sequence completion is to have this script run only until the event id is '100' that corresponds to the boot completion process in the system events
refer: http://www.howtogeek.com/72420/how-to-use-event-viewer-to-find-your-pcs-boot-time/
So, when you have this script in startup , it will poll all events and wait for event id to be 100 and alert you . the same can be employed in any scripting tool like autoit
Just wanted all to know it. because when i searched for this. all i found was the windows task scheduler idea or soluto at the best. actually soluto stopped working on my x64 pc a while ago for some strange reason. so i wanted to do a script myself which led me to this final solution....

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to copy google doc to another folder in google drive service I have a class that makes a copy of a google doc template file to then merge placeholders with data.  The problem is that it's creating the copy in the same folder as the original template file and I can't find a way to copy it to another folder.
Say I have a structure like so in google drive.
Main
    TemplateFiles
        MainTemplateDoc
    Contracts
        CopyOfMainTemplateDocAfterBeingMerged

As you can see, the CopyOfMainTemplateDocAfterBeingMerged doc wouldn't be located in the TemplateFiles folder where the original template was, but copied to the Contracts folder.
Is it possible to use the google drive v2 service to move the file after creating the copy?  I'm using the .net Google.Apis.Drive.v2 nuget package.  Here's the code that I have so far to create the copy.
private string CopyDocument(string documentId, string title)
{
    var newFile = new File { Title = title };
    var documentCopyFile = driveService.Files.Copy(newFile, documentId).Execute();
    return documentCopyFile.Id;
}

A: *

*You are using Drive API v2.

*You want to copy a file to the folder of Contracts.

*You have already been able to use Drive API.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
In this answer, I would like to propose the following modification.
From:
var newFile = new File { Title = title };

To:
var newFile = new File {
    Title = title,
    Parents = new List<ParentReference> {new ParentReference {Id = parentId}}
};

or
var newFile = new File() {
    Title = title
};
newFile.Parents = new List<ParentReference>() {new ParentReference() {Id = parentId}};

or
var newFile = new File();
newFile.Title = title;
newFile.Parents = new List<ParentReference>() {new ParentReference() {Id = parentId}};

*

*parentId is the folder ID of the folder Contracts.

Note:

*

*If you want to use Drive API v3, please use new List<string> {folderId} instead of new List<ParentReference> {new ParentReference {Id = folderId}}.

References:

*

*Files: copy

*Files: insert
If I misunderstood your question and this was not the direction you want, I apologize.


text:
Q: Flutter Error "not a subtype of type 'String' I am making a call to a class in a plugin to get a list of adresses, when I click on one I would like to show it on my TypeAheadField plugin. I can do all but actually show the selected text in the texfield of TypeAheadField. Here is my code for it
class SearchScreen extends StatefulWidget {
  @override
  _SearchScreenState createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
 TextEditingController dropOffTextEditingController = TextEditingController();

TypeAheadWidget usage
TypeAheadField(
    textFieldConfiguration: TextFieldConfiguration(
       ..............
    onSuggestionSelected: (suggestion) {
        print(suggestion);
        dropOffTextEditingController.text =
            suggestion;
    }),

Now the class in the plugin where the list for TypeAhead is coming from
import 'geo_point.dart';

class Address {
  final String? postcode;
  final String? name;
  final String? street;
  final String? city;
  final String? state;
  final String? country;

  Address({
    this.postcode,
    this.street,
    this.city,
    this.name,
    this.state,
    this.country,
  });

  Address.fromPhotonAPI(Map data)
      : this.postcode = data["postcode"],
        this.name = data["name"],
        this.street = data["street"],
        this.city = data["city"],
        this.state = data["state"],
        this.country = data["country"];

  @override
  String toString() {
    String addr = "";
    if (name != null && name!.isNotEmpty) {
      addr = addr + "$name,";
    }
    if (street != null && street!.isNotEmpty) {
      addr = addr + "$street,";
    }
    if (postcode != null && postcode!.isNotEmpty) {
      addr = addr + "$postcode,";
    }
    if (city != null && city!.isNotEmpty) {
      addr = addr + "$city,";
    }
    if (state != null && state!.isNotEmpty) {
      addr = addr + "$state,";
    }
    if (country != null && country!.isNotEmpty) {
      addr = addr + "$country";
    }

    return addr;
  }
}

class SearchInfo {
  final GeoPoint? point;
  final Address? address;

  SearchInfo({
    this.point,
    this.address,
  });

  SearchInfo.fromPhotonAPI(Map data)
      : this.point = GeoPoint(
            latitude: data["geometry"]["coordinates"][1],
            longitude: data["geometry"]["coordinates"][0]),
        this.address = Address.fromPhotonAPI(data["properties"]);
}

The error on the console
════════ Exception caught by gesture ═══════════════════════════════════════════
The following _TypeError was thrown while handling a gesture:
type 'SearchInfo' is not a subtype of type 'String'

How can I edit my code without affecting the plugin?

A: the error comes from this line
 dropOffTextEditingController.text =
            suggestion;

That's what we need to do :
 dropOffTextEditingController.text =
            (suggestion as SearchInfo)
                .address
                .name;


text:
Q: How to declare 2 interfaces with the same body? I have a base interface IInput and extended from it 3 interfaces IType1Input, IType2Input and IType3Input. After a few business changes to Type2(), IType2Input is now the same as IInput, but for consistency I don't want only Type2() to use IInput instead of an extended interface. I tried to do this:
    interface IType2Input extends IInput {}

ESLint then warned me about no-empty-interface. If I don't want to disable this rule, is there a way to declare IType2Input as the same interface as IInput?

A: Try using a type instead of an interface until that interface is different. Note that under the hood interfaces and types are the same.
type IType2Input = IInput;

A: I know you're not looking for this suggestion, so feel free to skip the following section.  This is mostly for future readers who come upon this question/answer pair.

I'd say that the no-empty-interface ESLint rule is not appropriate for your use case, and you really should disable the rule for the line in question without necessarily disabling it for your whole code base.
The documentation for the rule says "an empty interface is equivalent to its supertype ... [and therefore it] can be omitted." When you write
interface IType2Input extends IInput {} // linter warning!

and get a linter warning, the rule wants you to replace all references to IType2Input with IInput because IType2Input is redundant.  But you don't want to do this.  If you find a way to rewrite your code so that two equivalent interfaces named IType2Input and IInput exist without triggering the linter warning, you'd still be violating the spirit of the rule if not the letter.
Instead of trying to figure out how to circumvent the rule with syntax that might possibly be more complicated than an empty interface, you could just disable the rule for the one declaration, and comment it to let people know what you're doing and why:
// IType2Input is intentionally empty. It happens not
// to have more properties than IInput, but this may
// change in the future, and it helps to have a Type2-specific
// interface that people can use.  Therefore the no-empty-interface
// rule is not appropriate for this declaration:

// eslint-disable-next-line no-empty-interface
interface IType2Input extends IInput { }

From here on out I'll assume that you don't want to do this.

One way to circumvent the rule is to use the syntax for extending multiple interfaces, but the "multiple" interfaces are both just IInput:
interface IType2Input extends IInput, IInput { } // no error

This manages not to trigger the linter rule.  But, as you said, it's basically a hack.  And anyone who sees this code later would probably refactor it to just extends IInput, which would bring you back to the original problem.

Playground link to code


text:
Q: Bounds on entries of Cholesky factors? Motivated by the problem of covariance estimation.
Let $\Sigma$ be a positive-definite matrix whose diagonal entries are identically 1.  (i.e. $\Sigma$ is a correlation matrix.)
If $L$ is an lower-triangular matrix such that $L^T L = \Sigma$, can the entries of $L$ be bounded? (i.e. do there exist real numbers $l, u$ such that $l \geq (L)_{ij} \leq u$?)

A: OK, I'll post it as an answer. Since, by definition of $L$ and $\Sigma$, $\sum_i L_{i,j}^2 = \Sigma_{j,j} = 1,\,\,\forall j,$ we must have $|L_{i,j}| \le 1$.


text:
Q: Codeigniter: Make Trigger Update After Insert I have Table With Structure:
tb_berita

tb_kategori

nama_kategori in tb_kategori

I have a trigger named updateJumlahBerita have a function to
<p>**Update jumlah_berita + 1 In tb_kategori After Insert From tb_berita Where id_kategori(from tb_berita)=id_kategori(from tb_kategori)** :

    CREATE TRIGGER updateJumlahBerita AFTER INSERT ON tb_berita
    FOR EACH ROW
    BEGIN
       UPDATE tb_kategori
        SET jumlah_berita = jumlah_berita + 1
        WHERE id_kategori = id_kategori;
    END;

But the problem is, After i'm Insert Berita With kategori( let's say sport) All kategori +1 , but i want only SPORTto +1.
can you help me with this ?
 Thank's


text:
Q: Equivalence of verma modules Let $R^+$ be the set of positive roots and $L_\alpha$ the root space to $\alpha \in R^+$. $\mathfrak{h}$ is a Cartan subalgebra of L.
Let $I_\lambda$ be the left ideal of $U(L)$ which is generated by elements of the form $X \in L_\alpha$ for some $\alpha \in R^+$ and of the form $H-\lambda(H)$ with $H\in \mathfrak{h}$.
We define the Verma module
$$V(\lambda)=\mathcal{U}(\mathfrak{g})/I_\lambda$$
Let $F_\lambda$ be the one-dimensional F-vector space for $L_+=\oplus_{\alpha>0}L_{\alpha} \oplus H$  with action $h1=\lambda (h)1$ and $L_{\alpha}1=0, \forall \lambda >0$
I want to prove that $V(\lambda ) \cong U(L)\otimes_{U(L_+)}F_{\lambda}.$
So I define a left L-module homomorphism:
$$\phi : U(L)\to U(L)\otimes_{U(L_+)}F_{\lambda}, U \mapsto U\otimes 1_{\lambda}$$.
It is obvious that $I_{\lambda} \subset Ker\phi$, but I have trouble proving $I_{\lambda} = Ker\phi$.
Can you provide some hints?  Thank you!


text:
Q: How to run html local without Cors? I started an p5 project in p5s web editor. Now its getting big and I want to continue the project on my local Linux, but have no idea how to install a preview plug in there. before I used Atom on win 10 and it worked for me. But without the preview plug in I cant just preview the webpage html because of cors. Its a browser game and I have sprite and sound data in the html folder.
I tried an "allow cors" addon for firefox, but that doesnt make any difference.
I tried to start a localhost from terminal, and put an allow origin in the http header but I have no Idea how that goes.
I could might install Atom, but I dont know if the same plugins are working on linux. And I actually want to learn how professional web developers do get around it?
PS: I couldnt find anything that I understand or that solves my problem. I can understand if its not possible to post a solution for the cors error. Tipps for a nice and easy Linux Editor, or link to a tutorial, or solved thread would be great. THX

A: What you actually need is a web server (started from your terminal, and potentially with a command from your editor which will call the external command) which will serve your files. This has the advantage of being decoupled from your editor and this way you can change your tools or your environment without breaking your development workflow.
One way to do it is to add light-server to your project (There are a lot of alternatives to this tool tho, one of them being serve). To add it to your project you can use the following command:
npm install --save light-server

And then you can run the following command to serve your directory on localhost:4000 by default:
npx light-server -s .

To avoid using npx you can also install the server globally with this (that require to have your permissions properly configured for npm otherwise you'll get an error):
npm install --global light-server

And then you can use the command directly light-server -s .
You could also add the following to your package.json file to make the script easier to use:
"scripts": {
  "dev": "npx light-server -s . -w \"**/*\""
},

With that, running npm run dev in your project directory should start the webserver and reload the page each time you modify a file in the project.
Note that this kind of development server is also available in other languages if you need to (for example python). Using a webserver instead of loading directly the page from file:///path/to/index.html in your browser should fix your CORS issues.


text:
Q: Double limit $f_n(t_n) \to 0$ implies something about the limit of $f_n$? Suppose for each $n$, $f_n\colon (0,T) \to H$ is a map where $H$ is a Hilbert space. We know that
$$f_n(t) \to f(t)\quad(n \to \infty)$$ for fixed $t$ and $$f_n(t) \to 0\quad(t \to 0)$$
for fixed $n$ not necessarily uniformly in $n$.
Suppose also that there is a sequence $t_n$ which is decreasing and $t_n \to 0$ such that
$$f_n(t_n) \to 0\quad(n \to \infty).$$
Am I able to deduce any information about $f(t)$ near $t=0$ due to this?

A: No. Actually, this additional assumption follows from the previous one. For each $n \in \mathbb N$ one can choose $t$ such that $0 < t < \tfrac 1n$ and $|f_n(t)| \le \tfrac 1n$. If you denote this as $t_n$, you have $t_n \to 0$ and $f_n(t_n) \to 0$.
The functions $f_n(x) = 1 - (1-x)^n$ (i.e., rotated $x^n$) give a counterexample, as they converge pointwise to $f(x) = 1$.


text:
Q: Need to combine two list in scala with some condition for replacement I want to do this :
val list1 = List(Student("ivan","history",45))

val list2 = List(Student("ivan","history",40),Student("alexander","physics",81),Student("vlad","math",70))

I want to combine list1 and list2 so that list1's element remove list's 2 element based on student name and subject.
Required Output :
List(Student("ivan","history",45),Student("alexander","physics",81),Student("vlad","math",70))

A: You can define a function to check if two Student values match:
def isSame(s: Student, t: Student): Boolean = (s.name == t.name && s.sub == t.sub)

Using this you can iterate over list2 and check if there is a match in list1. If there is, you use the value from list1 else keep the value from list2.
list2.map(s2 => (list1.map(s1 => if (isSame(s1, s2)) s1 else s2))).flatten

Note that this might not be the most optimal solution if the two lists are huge.

A: I would go for a groupBy here. You concatenate the two lists, then you groupBy and take the head element for each key. This will scrumble the order among students though, but is efficient.
(list1 ++ list2)
  .groupBy(s => (s.name, s.subject))
  .map { case (key, values) =>
    values.head
  }


text:
Q: Unable to dual boot Vista and Ubuntu I am trying to dual boot old Vista with new  Ubuntu 11 10. I have done many things and arrived at the point where it will boot only to a grub> prompt where it stalls. I am able to run the Ubuntu live CD  but I cannot enter Vista (as I recently could) even after a repair with the installation Vista disk. That is to say that now Windows repair does not work.
While I have never been able to dual-boot as I should on this  laptop, I was able to boot into Windows Vista while I was playing around with Easy  BCD and almost every other command I could find. The most recent and immediate thing that I did  was to use a SystemRescueCD.
http://www.sysresccd.org/Main_Page
that was supposed to solve all my problems.  I ran each of the various options without benefit.
I read  that wiping the entire hard drive and reinstalling Windows may not affect the boot loader.  Is it correct that there boot codes somewhere on hardware affecting the boot process that I cannot change by wiping, format,  repartitioning and installing Windows?

A: If you're just trying to get Vista bootable again and then go from there, there's a few different ways you can go about trying to fix your boot loader.  The basic process is documented here:
http://www.lancelhoff.com/how-to-fix-vista-mbr-repair-broken-vista/
That should be a good place to start.


text:
Q: Program for making blu-ray slideshow movies of photos (simple, cheap or free)? Can you recommend a program for making blu-ray slideshow movies of photos (free or cheap)? for burning photo slideshow movies to blu-ray for watching on any standard settop consumer blu-ray player.
This is for a relative who would not wish to have to go through many steps to achieve the results. My research has found tools that look easy to use but only DVD based (we're in the HD 1080p era).
My Research so far:
(just so you know what I've already considered but not the answer.)
MemoriesOnTV - no HD blu-ray support
I'm looking for something like MemoriesOnTV, but a "MemoriesOnTV HD version" - would be what I'm looking for for blu-ray.
Memories on TV does not provide a feature for burning to Blu-ray
http://www.codejam.com/slideshow/index.htm
With HD TVs becoming commonplace, they need to catch up.
Photo DVD - looks good as well, but not blu-ray
http://www.vso-software.fr/products/photodvd/photodvd.php
Wedding Slideshow Studio - does Blu-ray cheesy Wedding theme interface, would prefer general purpose tool which this tool might be capable of.
http://www.wedding-slideshow-studio.com/how-to-burn-photo-to-blu-ray-disc.php
Searches on superuser...
Only found DVD-based answers
How to make a DVD movie of my photos?
Good Slideshow DVD programs?

A: Adobe Premiere Elements will do the job.
Here are the instructions:
http://help.adobe.com/en_US/PremiereElements/7.0/WS645B5E9D-30B2-4340-A06B-2B50117AE891.html
I have to say, these instructions by Adobe themselves could be better.
(I don't work for Adobe, by the way).

A: Premier is not in my opinion ideal it is very much video orientated. Proshow Gold or Producer is the industry standard for slideshow production on Windows (Fotomagicao for MAC)  cost for Gold version is about £70.00 and well worth it. Full support for DVD/Bluray/HD trial version is available from Photodex


text:
Q: How to save videos into database using asp.net mvc My requirement is to save images and videos into the database. I can successfully save the image into the database but I can't save the video in the database. Also, the video can be saved in a folder but the requirement is to save the video into the database. I am saving the image like this

A: Just read the InputStream as byte[]:
MemoryStream target = new MemoryStream();
poImgFile.InputStream.CopyTo(target);
byte[] data = target.ToArray();

And then store data to db.


text:
Q: Adding a working select element to an existing table I have a JavaScript function that adds a new row to a table. It works absolutely fine adding data types such as input (text), textbox, and radio. It also works using
document.createElement('select');
but as soon as I try to add elements, the button that triggers the JS function does nothing, which I assume means there's an error but I don't get any indication of what the problem is. I'm sure I've just missed something simple but it's been holding me back for hours and it's driving me insane!
The main body of the function is fine, because any other data type creates and adds itself to the table cell accordingly. An example of JS that works correctly within the function:
// inner left cell - text input
  var cellTwo = row.insertCell(1);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'col' + rowNumber;
  el.id = 'col' + rowNumber;
  cellTwo.appendChild(el);

The code to try and create a select element with working options: (N.B. this works if I comment out the options part and simply create an empty select element, so the error MUST be somewhere within the foor loop and must just be a result of my misunderstanding how to create options dynamically:
// inner right cell - select box
  var cellThree = row.insertCell(2);
  //create select element
  var dropDown = document.createElement('select');
  //give select element id and name
  dropDown.id = 'fieldtypecol' + rowNumber;
  dropDown.name = 'fieldtypecol' + rowNumber;

  //declare array values to put in option elements
  var optionValue[] = new Array('varchar(255)', 'int', 'date', 'float(53)');
  var optionText[] = new Array('String', 'Integer', 'Date', 'Float');

  //declare option element holder
  var option;

  //loop through creating and adding values to options
  for (var i = 0; i < 4; i++)
    {
    option = document.createElement('option');
    option.value = optionValue[i];
    option.text = optionText[i];
    //append current option before loop restarts
    dropDown.appendChild(option);
    }
  //append select element to new table cell
  cellThree.appendChild(dropDown);

Any help would be much appreciated, thanks.

A: It appears in your codes the lines;
var optionValue[] = new Array('varchar(255)', 'int', 'date', 'float(53)');
var optionText[] = new Array('String', 'Integer', 'Date', 'Float');

Should be;
var optionValue = new Array('varchar(255)', 'int', 'date', 'float(53)');
var optionText = new Array('String', 'Integer', 'Date', 'Float');

Types are dynamic in JS, I would have thought these errors would appear in the JS console for you.


text:
Q: Post custom media from Facebook App Canvas to user Feeds I am developing an Facebook Game App and I'd like to reward users to post custom media content (such as images and videos) from the Facebook app canvas to their own feeds. I just can't see Facebook supporting this based on their API Documentation.

A: You are not allowed to reward users for posting/liking/sharing etc...
Please read Facebook policy: https://developers.facebook.com/policy


text:
Q: Skip parameters from package documentation without warning I have created an R package and have set a generic with a few parameters having default values set to NULL. These parameters are not to be provided by the user and so I'd like to skip them from the documentation (using roxygen2) but not result in getting warnings in R CMD check.
An example:
#' Do that with myFoo...
#'
#' `myFoo` ...
#'
#' `myFoo` description...
#'
#' @param object An object of myBar class
#' @param a A numeric value...
#'
#' @return Smth
#'
#' @name myFoo
#' @export
#'
methods::setGeneric("myFoo", function(object, a, b=NULL, c=NULL) standard("myFoo"))

# User level
methods::setMethod(f="myFoo",
    signature=signature(object="myBar", a="numeric"),
    function(object, a, b, c){

            Some checks...

            b <- smth
            c <- smth

            return(myFoo(object@myBarItem, a, b, c))
    }
)

# For "iternal" use
methods::setMethod(f="myFoo",
    signature=signature(object="myBar2", a="numeric", b="character", c="matrix"),
    function(object, a, b, c){

            Smth

            return(someValue)
    }
)

A: The addition of @rdname and @aliases have solved the issue, as it seems.
#' Do that with myFoo...
#'
#' `myFoo` ...
#'
#' `myFoo` description...
#'
#' @param object An object of myBar class
#' @param a A numeric value...
#'
#' @return Smth
#'
#' @name myFoo
#' @rdname myFoo
#' @export
#'
#' @aliases myFoo,myBar,numeric,ANY,ANY-method
#' myFoo,myBar2,numeric,character,matrix-method
#'
#' @importFrom methods setGeneric setMethod
#'
methods::setGeneric("myFoo", function(object, a, b=NULL, c=NULL) standard("myFoo"))

# User level
methods::setMethod(f="myFoo",
    signature=signature(object="myBar", a="numeric"),
    function(object, a, b, c){

            Some checks...

            b <- smth
            c <- smth

            return(myFoo(object@myBarItem, a, b, c))
    }
)

# For "iternal" use
methods::setMethod(f="myFoo",
    signature=signature(object="myBar2", a="numeric", b="character", c="matrix"),
    function(object, a, b, c){

            Smth

            return(someValue)
    }
)


text:
Q: Middleware header is not working with laravel 7 Below is my code;
Route =>
Route::get('displayImage', function () {
return response()->file('uploads/sss.png');
})->middleware(['myHeader']);

myHeader =>
class AddHeaders
{
/**
 * Handle an incoming request.
 *
 * @param Request $request
 * @param Closure $next
 * @return mixed
 */

  public function handle(Request $request, Closure $next)
  {
    if ($request->header('token') != '123'
    || $request->header('token1') != '1234') {
        return response([
            "status" => false,
            "message" => "unauthorized"
        ]);
    }
    return $next($request);
}

}
Kernal.php
    protected $routeMiddleware = [
    'myHeader' => AddHeaders::class,
    'age' => CheckAuth::class,
    ];

If I don't add a header in postman then it returns me image; my header is not working. Plz, help.

A: You need to check if request has header using
$request->headers->has('your_header');

So middleware would look like below:
<?php

class AddHeaders
{
/**
 * Handle an incoming request.
 *
 * @param Request $request
 * @param Closure $next
 * @return mixed
 */

  public function handle(Request $request, Closure $next)
  {
    $has_token = $request->headers->has('token');
    $has_token1 = $request->headers->has('token1');

    if($has_token && $request->header('token') != '123' ||
        $has_token1 && $request->header('token1') != '1234' ||
        !$has_token || !$has_token1){
         return response([
            "status" => false,
            "message" => "unauthorized"
        ]);
    }

    return $next($request);
}

A: in your code u r just addeding new header you are  not protecting so as
here is the code for this from postman
u need to pass
in  Header
key           | value

token | 123
or
token1 | 1234

like this your route will protect
class AddHeaders
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */

    public function handle(Request $request, Closure $next)
    {
        if ($request->header('token') == '123'   || $request->header('token1') == '1234') {
            return $next($request);
        }

        return response([
            "status" => false,
            "message" => "unauthorized"
        ]);
    }
}


text:
Q: Why is electric heating so expensive? The loss of electricity in transmission and distribution is only 6%, so why is it that electric heating is so inefficient?
I would imagine that the generators at power plants are far more efficient than any engine you can put it in my house for heating, and I also assume there is very little energy loss from going to electrical energy to thermal energy (if not, then where does the energy go?).
Where am I going wrong in my thought process?

A: Your thought processes are fine as far as they go. What you are overlooking is the inefficiency of converting fuel to electricity. Dave Tweed mentioned it, but look at  https://www.nema.org/Products/Documents/TDEnergyEff.pdf for an overview. Yes, a central generating plant will do better than a home generator, but better is not nearly good enough.
Burning oil for heat will give efficiencies as high as 98%, although this takes some doing. 80 - 90% is more typical. A conventional coal-fired electrical generating station will run in the neighborhood of 40%. Add on another 6 - 8% transmission loss, and a good general number for relative efficiencies is 2:1 in favor of non-electric heating. There are economies of scale associated with central plants (transportation of fuel is cheaper, for instance, since there is no need for a local distribution network to get the fuel to individual homes), but these are not nearly enough to overcome the basic problem of generator inefficiency.

A: For the same reason it would be uneconomical to burn fine furniture in your fireplace rather than raw logs. Electricity is a more useful and expensive form of energy than heat, and you lose the majority of the energy in the fuel turning it into electricity in a thermal plant (even with a large well-designed plant, about half to two thirds is lost!). When you burn natural gas directly, most of the heating energy goes into your house (in our case, with a high-efficiency furnace, the lost heat is so low that a small plastic tube is used as the "chimney", so you know most of the heat goes into the heat exchanger).
You are correct, however, that centralized large installations have efficiencies. Your own standby electric generator would not be as efficient as the thermal power station. Crowded downtown areas sometimes have central heating plants. For example, in Toronto there is a plant that supplies about 0.6GW of steam to 140 buildings downtown.

A: The efficiency of converting electricity to heat is 100% (although sometimes some of the heat ends up in places you don't want it).
However, the conversion of fuel to heat, the conversion of heat to mechanical energy and the conversion of mechanical energy to electricity are far from 100% efficient. Look up Carnot cycle for some insight into the fundamental physical limitations.
This is why it is always more efficient to convert fuel directly into heat in your home.

A: If you're looking at cost efficiency as well as energy efficiency, an additional factor is that a significant fraction of your electric bill is for the maintenance and operation of the grid instead of power generation.  Depending on where you live those costs may be broken out separately on your bill: on mine they collectively make up about 4 of the 12 cents I pay per kWH of (coal generated) power.

A: I believe there are two questions conflated here. One is thermodynamical (Carnot) efficiency and the other is cost in real money. I believe that the heat pump (mentioned in a few answers already) can be more Carnot efficient (even with the coal-generated electricity) than the direct combustion.
There is a nice book that discusses these issues, "Without the Hot Air" by David MacKay. http://www.withouthotair.com/

A: Short: The price is set by a team consisting of the invisible hand and involved regulatory and government agencies.
Longer: Electricity costs what the overall market will bear.
This includes
cost of capital for plant and transmission lines,
cost of maintenance,
fuel where needed,
depreciation (= amortised cost of replacement),
plus profit
less subsidies.
"Profit" as a % of costs in a competitive market is adjusted so that volume sold x profit % is maximised.
You hope.
All the other generators do this as well and the system oscillates and the regulators regulate and some scrape by and some go broke and the long term average profit is usually about 0%.
When this stable state is reached the cost is whatever it takes to achieve it.


text:
Q: Cardinalidade em Banco de Dados - Relacionamento Um para UM estou estudando banco de dados, e no momento além das definições de banco, tipo de modelos estou vendo Cardinalidade!
Estou com dúvidas nesse exercício abaixo:

Minhas dúvida são as seguintes

Como eu identifico a a origem e o destino desse relacionamento?

Pois para mim a origem seria Boleto e o Destino Pagamento..

Também queria saber se meu pensamento sobre cardinalidade está correto!

A cardinalidade (0,1) para o boleto e (1,1) para o pagamento... Estou certa?
Mas a resposta do exercício é :
Origem (min=1, max=1) e Destino (min=0, max=1)
Ou seja- Aparentemente: o pagamento como Origem e o Boleto como destino!

A: Há um erro de conceito na postagem.
O termo "cardinalidade" refere-se a quantidade de instâncias de um objeto associadas a outro. Normalmente é utilizado quando tratamos de um diagrama de objetos.
O termo correto seria "multiplicidade", o qual define as quantidades mínima e máxima às quais um objeto pode estar associado. Este termo sim é utilizado em um modelo de banco de dados ou em um diagrama de classes.
Veja o exemplo abaixo:

Agora respondendo as questões:
Em um modelo desse tipo, não existe a ideia de origem e destino, pois não há um fluxo de informação; o que existem são relacionamentos entre entidades. Assim, o que está representado no diagrama é o seguinte:
"A entidade t_boleto está associada a um único t_pagamento (1..1), enquanto que um t_pagamento está associado a um único t_boleto também (apesar de não declarado, quando não há indicação de multiplicidade, entende-se que o valor é 1..1, conforme o metamodelo da UML)."
A resposta dada ao exercício não me parece correta, mas parece que realmente considera o t_pagamento como Origem e t_boleto como Destino e não sei qual foi a base para isso.


text:
Q: Best Approach to using Top and Count - SQL Server 2008 I have an 2008 C# application (back end SQL Server 2008) where sometimes queries return a large number of results.  So, I researched some paging algorithms and put one in place that uses the TOP statement.  I love the fact that if I have 500 total results and am only showing 20 results per page that I can only query the database for 20 records instead of storing all 500 records in memory.
The issue I have though is that in order to implement the paging algorithm, I need to know how many total records there are in this query.  So, what I have done is to just run another query with the same parameters that just selects the ID (instead of the whole object) to try to make it run quickly.  For some reason though, I think that running these two queries (thus establishing 2 connections) isn't the best approach.
So I need the count of all of the records but only want to select the limited number used in TOP.  Would a temporary table be of use here?  I have two different stored procedures now.
Thanks for any "best practices" advice anyone can give.

A: You could use object datasource...to implement this custom paging.

A: I would use ROW_NUMBER() OVER (ORDER BY ...). More details here.

A: I don't know what approach that you are taking for paging however the technique that I usually use is to use the ROW_NUMBER function, for example:
SELECT  Description, Date
FROM
(
    SELECT  ROW_NUMBER() OVER (ORDER BY Date DESC) AS Row,
        Description, Date
    FROM Log
) AS LogWithRowNumbers
WHERE  Row >= 1 AND Row <= 10

This approach is the cleanest that I am aware of, works with any subquery and only requires a single query.
Of course if you wish to show a "total hits" or similar on your page then you will also need another query to get the row count:
SELECT COUNT(*) FROM Log

However you can execute both statements in the same batch to prevent the need for an extra "round trip" to the databse server.
Source - Paging Records Using SQL Server 2005 Database - ROW_NUMBER Function

A: If you perform both selects within your stored proceedure you would get two datatables in your dataset after using the Fill method.

A: I would try something like this:
;WITH CTE AS
(
    SELECT
        ROW_NUMBER() OVER (ORDER BY Date DESC) AS Row,
        COUNT(*) OVER() AS TotalCount,
        Description, Date
    FROM Log
)

SELECT *
FROM CTE
WHERE Row BETWEEN 1 AND 10

This will provide both paging and a count in 1 query.  You could also use a CASE statement to only do the count at certain times.  For instance does the count change while users are paging through?


text:
Q: Access forbidden for identity on javascript Twilio chat SDK I'm using twilio chat javascript SDK and I'm having problems when I try to create a new channel and invite a user.
Both users (sender and receiver) receive this error:
Error: Access forbidden for identity
But if I go to the dashboard, the channel is created with the 2 members.
What am I doing wrong?
PS: I'm creating user tokens as listed on Twilio API, I don't believe token could be a problem because the message is already sent.
It seems the problem happen when I join the channel.
My code to create the channel:
this.client.createChannel({
  uniqueName: roomName,
  friendlyName: 'My Channel',
  type: 'private'
}).then(channel => {
  this.channel = channel
  this.channel.join()
});

My invite code is just:
this.channel.invite(user)

and to generate  user tokens:
new Fingerprint2().get(fingerprint => {
  this.fingerprint = fingerprint

  let AUTH_TOKEN = $('meta[name=csrf-token]').attr('content')

  fetch('/chat/tokens', {
    method: 'POST',
    body: JSON.stringify({
      fingerprint: fingerprint,
      authenticity_token: AUTH_TOKEN,
      email: email
    }),
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content'),
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(result => result.json()).then(data => {
    callback({ token: data.token, username: data.username })
  })
})

and on my API
user = User.find_by_email(params[:email])

account_sid = ENV['TWILIO_ACCOUNT_SID']
api_key = 'SKe9fcdbefe0bdc1f01af4aa50d3548b70'
api_secret = 'oslALMC18tCZrUhBRDPin5KbqPSR9Rr4'

service_sid = ENV['TWILIO_SERVICE_ID']
device_id = params[:fingerprint]
identity = user.username
endpoint_id = "FakeEndPoint:#{identity}:#{device_id}"

grant = Twilio::JWT::AccessToken::IpMessagingGrant.new
grant.service_sid = service_sid
grant.endpoint_id = endpoint_id

token = Twilio::JWT::AccessToken.new(
  account_sid,
  api_key,
  api_secret,
  [grant],
  identity: identity
)

render status: 200, json: { token: token.to_jwt, username: user.username }

a token sample:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0eSI6InR3aWxpby1mcGE7dj0xIn0.eyJqdGkiOiJTS2U5ZmNkYmVmZTBiZGMxZjAxYWY0YWE1MGQzNTQ4YjcwLTE1MDExNjA0MjAiLCJncmFudHMiOnsiaWRlbnRpdHkiOiJqb25hdGFzIiwiaXBfbWVzc2FnaW5nIjp7InNlcnZpY2Vfc2lkIjoiSVMwYThiM2NkYTllMTU0YTUyOTg3MjJkOTRjOTI5ZjBhOSIsImVuZHBvaW50X2lkIjoiSGlwRmxvd1NsYWNrRG9ja1JDOmpvbmF0YXM6ZmU2NGZjYTA5NDc4YjYzNjNlYTFiMzA3OGQzOTQwM2MifX0sImlzcyI6IlNLZTlmY2RiZWZlMGJkYzFmMDFhZjRhYTUwZDM1NDhiNzAiLCJuYmYiOjE1MDExNjA0MjAsImV4cCI6MTUwMTE2NDAyMCwic3ViIjoiQUMxN2VmODM5N2JhODJkZWQ2ZDlmZmE0ODFkMWI2YTczMSJ9.UF8XtcEBN8LSCKVvBRscu9CmYdgMVobTd84RowF5KaU

A: Twilio developer evangelist here.
When you join a channel (with channel.join()) the promise resolves when the request to join the channel succeeds. This doesn't mean that the channel has been completely joined yet.
Instead, you should listen for the channelJoined event on the chat client. Once that fires you can be certain you are now a member of that channel and can interact with it.
So, if you join a channel, you should listen for the event like this:
this.client.on('channelJoined', function(channel) {
  console.log('Joined channel ' + channel.friendlyName)
})

this.client.createChannel({
  uniqueName: roomName,
  friendlyName: 'My Channel',
  type: 'private'
}).then(channel => {
  this.channel = channel
  this.channel.join()
});


text:
Q: C# Structure - Forms, Panels and User Controls I use PHP all the time but am completeley new to C#. Obviously with webpages and apps everytime a user clicks a new page is loaded or javascript is used to inject content.
When designing my C# app with Microsoft Visual Studio 2010 Express I am having trouble understanding how my app is supposed to structure. I have a form with buttons.... when a button is pressed it goes to that category and shows more buttons(Fairly Simple).
At first I was going to have a form with main buttons. When a button is pressed it closes and a new form opens. Apparantly this is not a good idea. I was than going to use panels on the one form which shows and than hidden as needed.
Now I am reading on the internet that I should be using User Controls????
If you think User Control than why bother having the panel? Why not just put the user controll on the form?
What is the correct way to reload content onto the form? The content will be dynamic from an SQL database.

A: It depends on your requirements. Usually winform applications have single main form, which contains a single panel - with tabs/user contols/buttons/etc, opening modal windows (on top of main form, which should be closed to come back to main form) or MDI (multi-document) interface, (a nice example of implementation), like Word/Photoshop/etc, when different documents open as child windows for main form and user can navigate between them back and forth. This can be used for multiple database records application. For example, main form with menu/toolbar (like outlook inbox/sent/etc), single window for searching documents, double-click - opens document details in a new window, etc.
You might use Panel or UserControl as a container, which fits your needs. Usually Panel is used just as container, while UserControl - as inherited control with some custom behavior/controls. You might add Name [...textbox...] UI into parent control. Or into inherited UserInfoControl : UserControl with Last Name, Birth Date, etc. And reuse it in multiple places.


text:
Q: Copy the value to rows for distinct values - Spark dataframe I have a spark dataframe. I want to copy the value of rows based on the specific column
ColumnA  columnB columnC
a         Null      Null
a          1          1
b          2          2
c          Null      Null
c          3          3

So in this dataframe ColumnC is a copy of ColumnB but , I want a single value for each value in ColumnA. If a value of Column A has null and a proper value, I want proper value in all places else Null.
Required dataframe:
ColumnA  columnB columnC
a         Null        1
a          1          1
b          2          2
c          Null       3
c          3          3

I tried doing partitionby(ColumnA) but seems not working.
Can I get a scala code for this

A: If I understand correctly, you are looking to choose a B value for every A value.
This is a groupBy clause.
In order to correctly choose the value you need to find the proper aggregation function. In this case, the first function can be used:
import org.apache.spark.sql.{functions => F}

df
  .groupBy($"columnA")
  .agg(F.first($"columnB", true) as "columnC")

This will give you a single value from B for every value A
columnA  columnC
a        1
b        2
c        3

You can then proceed to join it with the original DF by A.


text:
Q: Xcode NSUserDefaults turn NULL/nil after a few screens Have an app - Xcode 11, iOS 13 - that has (so far) 8 screens. On the first screen the user keys in his/her last and first names and I use the following to store (and it works)
NSString *value1 = _lastName.text;
NSString *value2 = _firstName.text;
NSLog(@"Firstname: %@", value1);
NSLog(@"Lastname: %@", value2);
NSUserDefaults *saved = [NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults] setObject: value1 forKey:@"curLast"];
[[NSUserDefaults standardUserDefaults] setObject: value2 forKey:@"curFirst"];
[saved synchronize];

One the 2nd screen another string is saved (and it works)
[[NSUserDefaults standardUserDefaults] setObject: newvalue forKey:@"curData"];
[[NSUserDefaults standardUserDefaults] synchronize];

I use curData on the next 3 screens - works. On the 5th screen I use the curLast and curFirst - works. But on the next screen I try to retrieve the curLast and curFirst again:
NSString *lsaved = [[NSUserDefaults standardUserDefaults]
                            stringForKey:@"curLast"];
    NSString *lsaved2 = [lsaved stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *fsaved = [[NSUserDefaults standardUserDefaults]
                        stringForKey:@"curFirst"];

    NSLog (@"Last%@ First %@", lsaved2, fsaved);

They are both (null).
I've seen other SO threads about this but on earlier versions and allegedly there was a fix. Are suggestions?


text:
Q: Return only one row from Oracle SQL, using outer join and case statement I'm trying to figure out how to just return one row per result, even if there are multiple activities ('act's) per result. I've read and searched to no avail.
What I want:
Date       Site Result act1 act2

1985-06-10 1008 NT6    5    10

What I get:
Date       Site Result act1 act2

1985-06-10 1008 NT6    5
1985-06-10 1008 NT6         10

Here's my (example) code, which I know is not broken, but it's the path I tried. I just don't know how to obtain what I want.
SELECT
t."Date",
t."Site",
t."Result",
CASE
  WHEN a.Type = 'act1'
  THEN a.Count
END AS "act1",
CASE
  WHEN a.Type = 'act2'
  THEN a.Count
END AS "act2"
FROM
(
SELECT Sample.SAMPLE_ID,
       Sample.Date,
       Sample.Site,
       Sample.Result
FROM   Sample
WHERE  Sample.Date is Between then and now
) t
LEFT OUTER JOIN
ACTIVITY
ON (ACTIVITY.SAMPLE_ID = t.SAMPLE_ID)

A: here you go
select t."Date", t."Site", t."Result",
        sum(case when a.Type = 'act1' then a.Count else 0 end ) AS act1,
        sum(case when a.Type = 'act2' then a.Count else 0 end ) AS act2
from   sample left outer join activity
        on (activity.sample_id = t.sample_id)
where  sample.date is between then and now

and don't use braces on column names.


text:
Q: QMetaObject::invokeMethod does not take a non const argument I am doing a project with Qt where in invoke method runs on a seperate thread and called from main thread.
If I pass a QByteArray as const it builds and runs.
However if I remove the const it builds but terminates when I try to run it,
and throws an assert Q_ASSERT(b).
Why is it getting terminated?
I have to append some data into QByteArray.
const bool b = QMetaObject::invokeMethod(m_thread, "calculateSpectrum",
                              Qt::AutoConnection,
                              Q_ARG(QByteArray, buffer),
                              Q_ARG(int, format.frequency()),
                              Q_ARG(int, bytesPerSample),
                              Q_ARG(qint64, dataLength));
    Q_ASSERT(b);
    Q_UNUSED(b) // suppress warnings in release builds

A: basically the signature of QMetaobject::invokemethod is...
bool    invokeMethod ( QObject * obj, const char * member, Qt::ConnectionType type, QGenericReturnArgument ret, QGenericArgument val0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QGenericArgument(), QGenericArgument val4 = QGenericArgument(), QGenericArgument val5 = QGenericArgument(), QGenericArgument val6 = QGenericArgument(), QGenericArgument val7 = QGenericArgument(), QGenericArgument val8 = QGenericArgument(), QGenericArgument val9 = QGenericArgument() );

now in this we are using the Q_ARG macro whose syntax is..
QGenericArgument    Q_ARG ( Type, const Type & value )

which requires a const parameter.
Now when u remove this const parameter the condition becomes false and it will throw an assert at runtime.


text:
Q: Is it possible to add an ActionListener in choice in GUI? list.addActionListener(this);

I got an error of cannot find symbol though I used it in JButton and was accepted.

A: Look through the methods of JList in the docs.  (that's what they are for).  The docs. will tell you exactly what type(s) of listeners can be added to a component.
Be sure to also check the methods of the super classes (which are inherited by the class).  Scroll further down to see them.


text:
Q: webpack scss to css creating blank css file (vs 20017 .net core react) When I run my webpack task to create a css file from scss I end up with a blank css file.  I'm not sure if the config settings are wrong, or something else.
Background
I've set up a new test project in VS2017 .net core using the react template. This automatically created the webpack.config.js and webpack.config.vendor.js files for me.  Under the vendor config there was a setting for css which does the bootstrap css minimization.  I wanted to add a 3rd party scss (breakpoint-sass which is under node-modules) and do the same thing but scss to css and then min for prod. I've added in the config settings and used ExtractTextPlugin to extract it to a separate file (just to confirm it was working) but when I run the webpack I get a blank file. I've installed the sass loader.
Package.json (just in case its a version issue)
{
  "name": "CoreReactTest",
  "private": true,
  "version": "0.0.0",
  "devDependencies": {
    "@types/history": "4.6.0",
    "@types/react": "15.0.35",
    "@types/react-dom": "15.5.1",
    "@types/react-hot-loader": "3.0.3",
    "@types/react-router": "4.0.12",
    "@types/react-router-dom": "4.0.5",
    "@types/webpack-env": "1.13.0",
    "aspnet-webpack": "^2.0.1",
    "aspnet-webpack-react": "^3.0.0",
    "awesome-typescript-loader": "3.2.1",
    "bootstrap": "3.3.7",
    "css-loader": "0.28.4",
    "event-source-polyfill": "0.0.9",
    "extract-text-webpack-plugin": "2.1.2",
    "file-loader": "0.11.2",
    "isomorphic-fetch": "2.2.1",
    "jquery": "3.2.1",
    "json-loader": "0.5.4",
    "react": "15.6.1",
    "react-dom": "15.6.1",
    "react-hot-loader": "3.0.0-beta.7",
    "react-router-dom": "4.1.1",
    "style-loader": "0.18.2",
    "typescript": "2.4.1",
    "url-loader": "0.5.9",
    "webpack": "4.0.1",
    "webpack-hot-middleware": "2.18.2",
    "gulp": "3.9.1",
    "gulp-less": "4.0.0",
    "gulp-sass": "3.1.0",
    "node-sass": "4.7.2",
    "sass-loader": "6.0.6",
    "resolve-url-loader": "2.2.1",
    "breakpoint-sass": "2.7.1",
    "@types/lodash": "4.14.104",
    "lodash": "4.17.5"
  }
}

Webpack Vendor Config
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = (env) => {
    const extractCSS = new ExtractTextPlugin('vendor.css');
    const isDevBuild = !(env && env.prod);
    const extractSass = new ExtractTextPlugin({
        allChunks: true,
        filename: 'vendor2.css'})
    return [{
        stats: { modules: false },
        resolve: {
            extensions: [ '.js', '.scss' ]
        },
        module: {
            rules: [
                { test: /\.(png|woff|woff2|eot|ttf|svg)(\?|$)/, use: 'url-
                loader?limit=100000' },
               { test: /\.css(\?|$)/, use: extractCSS.extract([isDevBuild ?
               'css-loader' : 'css-loader?minimize']) },
               {
                    test: /\.scss$/,
                    include: [/(src)/, /(node_modules)/],
                    exclude: /fonts/,
                    use: extractSass.extract({
                        fallback: 'style-loader',
                        use: ['css-loader', 'sass-loader']
                    })
                }

            ]
        },
        entry: {
            vendor: ['bootstrap', 'bootstrap/dist/css/bootstrap.css', 'event-source-polyfill', 'isomorphic-fetch', 'react', 'react-dom', 'react-router-dom', 'jquery', 'breakpoint-sass', 'breakpoint-sass/stylesheets/_breakpoint.scss'],
        },
        output: {
            path: path.join(__dirname, 'wwwroot', 'dist'),
            publicPath: 'dist/',
            filename: '[name].js',
            library: '[name]_[hash]',
        },
        plugins: [
            extractCSS,
            extractSass,
            new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }),
            new webpack.DllPlugin({
                path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
                name: '[name]_[hash]'
            }),
            new webpack.DefinePlugin({
                'process.env.NODE_ENV': isDevBuild ? '"development"' : '"production"'
            })
        ].concat(isDevBuild ? [] : [
            new webpack.optimize.UglifyJsPlugin()
        ])
    }];
};

I've added the extractSass const, scss test to rules, and 'breakpoint-sass/stylesheets/_breakpoint.scss' to entry.  The _breakpoint.scss is the top level file, there are sub-folders and scss files that are required as well, so I'm not sure if this entry text is correct.
In my config it creates a vendor2.css file when I build the webpack but it is blank so not sure what I've done wrong? The css one runs and creates vendor.css when has all the bootstrap css in it.


text:
Q: Getting the wrong URL I am trying to get the current URL in Google HTML services , But I do not get the correct one , I use the following methods.
function pprueba(url){
console.log("Prueba : "+url);
console.log("Pruena 2 :"+window.location.href);
console.log("Pruena 3 :"+google.script.run.getScriptUrl());
console.log("Pruena 4 :"+window.location);
console.log("Pruena 5 :"+$(this).attr('href'));
}

in the server side I have this function , the first prueba are getting as parameter the result of getScriptUrl.
function getScriptUrl() {
    var url = ScriptApp.getService().getUrl();
    return url;
}

Prueba : https://script.google.com/macros/s/AKfycbwaCJjgSiUs6LiQq0yocXNU93DVtD30lLTEWi1NEcs/dev
Pruena 2 :https://n-4xmbqpfn3z7t4od5wj623x3uicdbwgqeelan7da-0lu-script.googleusercontent.com/userCodeAppPanel
Pruena 3 :undefined
Pruena 4 :https://n-4xmbqpfn3z7t4od5wj623x3uicdbwgqeelan7da-0lucript.googleusercontent.com/userCodeAppPanel
Pruena 5 :undefined
but  what I expect is
https://script.google.com/a/CompanyName.com/macros/s/AKfycbwaCJjgSiUs6LiQq0yocXNU93DVtD30lLTEWi1NEcs/dev


text:
Q: Непонятный код, цикл и поля Цикл: for (j = 2; j < i; j++), в чем заключается j<i. Как это понять? Откуда мы придумали j?
public class Za {
  public static void main(String args[]) {
    int i, j; // Объявление переменных i и j.

    boolean isprime; // Объявление переменной isprime

    for (i = 2; i < 100; i++) { // Объявление цикла
      isprime = true; //Вопрос: Зачем здесь это?

      for (j = 2; j < i; j++) /* Не ясно объявление цикла? Ведь i=2,
         а тут опять пишем j=2 и еще пишем j<i (как это возможно если Они оба
         равны 2). Вообще зачем, что написали внутри цикла */

        if ((i % j) == 0)
          isprime = false; // Непонятно, почему мы делим по модулю  и
                           // если без остатка вернется false

      if (isprime) // Не понятно эта управляющая конструкция
        System.out.println(i + " is prime.");
    }
  }
}

// Почему создается это:

isprime = true;
// Проверить, делится ли число без остатка.
for (j = 2; j < i; j++)
  // Если число делится без остатка, оно простое
  if ((i % j) == 0)
    isprime = false;

A: Дописал пояснения комментариями в коде:
for (i = 2; i < 100; i++) { // перебираем все числа от двух до ста
  isprime = true; // если не доказано обратное - число простое

  for (j = 2; j < i; j++) //  перебираем все числа от двух до текущего числа (хотя достаточно до Sqrt(i))

    if ((i % j) == 0)
      isprime = false; // если остаток равен нулю, то текущее число i делится нацело на делитель j и простым быть не может. После этого должен стоять break, т.к. дальше искать делители бессмісленно

  if (isprime) // если не было найдено ни одного делителя, то число простое
    System.out.println(i + " is prime.");
}

A: Это алгоритм поиска простых чисел до 100, второй цикл это все числа меньше i-го для проверки(поэтому и j < i), а isprime - это обычный флаг, который в итоге проверяется для отображения числа в консоль.

A:
//  и это не ясно почему мы так сделали? ведь i=2 а тут опять пишем j=2

У вас i=2 только в первой итерации цикла по i, во всех последующих нет.

// и это не ясно, почему мы делим по модулю  и говорим если  без остатка то ошибка ( false)

Опять неверно, если делится без остатка то присваиваем булевой переменной значение false, а не ошибка.
А вообще:

Домашние задания надо выполнять самостоятельно. Если у вас возник вопрос по домашнему заданию, не просите его сделать за вас. Задайте конкретный вопрос о проблеме, которую вы не можете решить. Программирование — это то, в чём надо разбираться самому, либо не заниматься им вовсе. Если для вас программирование — лишний предмет в учебной программе, есть сайты и люди на этих сайтах, выполняющие задания за материальное вознаграждение. Здесь предлагать выполнить работу за вас и наоборот — моветон.

A: Смысл в том, что это циклы, и ты говоришь, что выполняй внутренний цикл пока j < i, как только это неравенство перестанет выполняться то выйди из цикла. Это имеет смысл так как следующий раз i будет равно 3 4 5 и т.д. до 10


text:
Q: turn off blur events and use 1 button to update fields I  have a website that manages accounts of agents. Fields are updating when blur event occurs, but i created one UPDATE button to update the fields by clicking on it. Now i want to disable those blur events and update fields by using one UPDATE button instead of updating fields one by one by blur events.
Sorry if this has a simple solution, I'm just new to scripting.
index.php
$(document).on('blur', '.username', function() {
  var id = $(this).data("id7");
  var username = $(this).text();
  edit_data(id, username, "username");
});

$(document).on('blur', '.password', function() {
  var id = $(this).data("id8");
  var password = $(this).text();
  edit_data(id, password, "password");
});

function edit_data(id, text, column_name) {
  $.ajax({
    url: "edit.php",
    method: "POST",
    data: {
      id: id,
      text: text,
      column_name: column_name
    },
    dataType: "text",
    success: function(data) {
      //animations and effects
      $('body, html').animate({
        scrollTop: 0
      }, 100);
      $("alert").delay(3200).fadeOut(300);
      document.getElementById("alert").style.visibility = "visible";
      document.getElementById("alert-cont").innerHTML = data;

    }
  });
}
$(document).on('click', '#update_btn', function() {

  ////CODE TO DISABLE BLUR EVENTS AND UPDATE .username and .password fields BY SINGLE CLICK
});

anotherpage.php
this is where the '.username' ,'.password' and '#update_btn' came from.
$output. = '

  <td class="id" data-id10="'.$row[" id "].
'" '.$row["username"]. '

  '.$row["password"]. '

  <button type="button" name="up_btn" id="update_btn" data-id12="'.$row[" id "].
'" onclick="update()">UPDATE</button>

';


text:
Q: Check if TextBox is created, then assign it's value I'm trying to make a small app, for make my job easier creating definitions (new web forms aspx) via WinForms C#.
Now I have this form, where I tell the app how many textboxes I want to create.
After their creation, I want to assign to a string the textboxes values that I wrote.
    private void CreateControls()
    {
        for (int index = 0; index < NumberOfRows; index++)
        {
            TextBox textBox = new TextBox();
            textBox.Name = "TextBox" + (index + 1).ToString();
            textBox.Size = new Size(120, 20);
            textBox.Location = new Point(X, Y + 26);

            ComboBox comboBox = new ComboBox();
            comboBox.Name = "ComboBox" + (index + 1).ToString();
            comboBox.Size = new Size(75, 20);
            comboBox.Location = new Point(141, Y + 26);
            comboBox.DataSource = Enum.GetNames(typeof(DataTypes));

            Y += 26;

            this.Controls.Add(textBox);
            this.Controls.Add(comboBox);
        }
    }

Now, I don't know how to check if the textboxes are created, and then take their values.
Could anyone refer me something? Thanks :)!

A: You'll need to, on Page_Load, find those controls and grab their values. Since you gave them meaningful names when you created them, this should do the trick:
for (int index = 0; index < NumberOfRows; index++)
{
    TextBox textBox = this.FindControl(
        string.Format("TextBox{0}", index)) as TextBox;
    if (textBox == null) { continue; }  // this means it wasn't found

    var text = textBox.Text;
    // work with the text
}

However, if the ComboBox class you're using isn't a third-party one and it's not an ASP.NET application, the code would work for a Windows Forms application as well with a minor modification:
for (int index = 0; index < NumberOfRows; index++)
{
    // you have to use the Find method of the ControlCollection
    TextBox textBox = this.Controls.Find(
        string.Format("TextBox{0}", index)) as TextBox;
    if (textBox == null) { continue; }  // this means it wasn't found

    var text = textBox.Text;
    // work with the text
}

I tend to agree with the community that it's probably a Windows Forms application because you can't set the Location of a standard ASP.NET control. However, if these are user controls, or third-party ones, that support those properties and render the appropriate CSS then we'd never know.

A: if(Page.FindControl("IDofControl") != null)
   //exists
else
   //does no exists


text:
Q: How to create a Singleton timer with a coroutine for a Kotlin Android app with various fragments? In my android app, which I made in Kotlin, I used a Timer and a Runnable to repeat a certain set of tasks.
However, I quickly ran into issues, as my app had a bottom navigation and therefore, everytime I clicked on a different navigation item like (home, profile, settings, etc) and returned back to the fragment with the Runnable, the timer was behaved erratically. It seemed to me that multiple timers were being created and somehow, were not being destroyed.
A quick solution was to use a Singleton so initialize one instance with a timer and synchronize it with whatever function I want it to repeat.
However, coming from Java I had no knowledge of using a Singleton in Kotlin. I did some research and found out that to make a singleton, you declare it as object SingletonName and you just use it. It's that simple (as mentioned by various dev blogs)
So, I basically want a timer to be in a singleton and then repeat a certain amount of tasks in a fragment with a runnable, without ever having to maintain another timer.
How do I achieve it?

A: Creating a Singleton was easy. As easy as writing
object SyncTimer {

    //TODO:Your code here

}

Since, I was doing UI operations, I wanted to use a Co-routine, which will be maintained in the Singleton itself.
So I added the dependency in my build.gradle (app level)
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2"

Next up, we create the co-routine with the runnable. For my usage, I'll initialize the runnable in my Dashboard.kt file. The Dashboard activity contains all my other fragments in the bottom navigation (home, profile, settings, etc.)

object SyncTimer{
    //You can supply your own runnable from Fragments
    private lateinit var userRunnable: Runnable

    fun init (){
        val handler = Handler()

        GlobalScope.launch {

            if(userRunnable == null){
                userRunnable = Runnable {
                    Log.d("SyncTimer", "Working without any inputs")
                }
            }

            val swipeTimer = Timer()
            swipeTimer.schedule(object : TimerTask() {
                override fun run() {
                    handler.post(updateUi())
                }
            }, 1000, 2000)
        }
    }

    fun set(runnable : Runnable) {
        Log.d("SyncTimer", "A runner was provided")
        userRunnable = runnable
    }

    private fun updateUi(): Runnable{
        return userRunnable
    }

}

Then in my Dashboard activity, I initialize the Runnable like in the onCreate()
        SyncTimer.init()

With this, the timer and runnable have initialized. My dashboard quickly defaults to the HomeFragment, where in the onCreateView() I pass a runnable of my own to the set():
val updateUi = Runnable {
                //Your code here
        }

        SyncTimer.set(updateUi) // <- Pass your runnable here

If you have noticed, I've used an if statement in the singleton, where if userRunnable == null then pass a default runnalbe, that prints into the logs, "Working without any inputs"
However, when my app starts, I always get "A runner was provided" in the logCat. This means that the Runnable worked right from the first instance, with the runnable I passed on to it with the SyncTimer.set()
Now, even if I change to different fragments, the timer is maintained. and Only when I return to the HomeFragment the code to update ui is called again.
Therefore the cleanest version of the code is:

object SyncTimer{
    private lateinit var userRunnable: Runnable

    fun init (){
        val handler = Handler()

        GlobalScope.launch {
            val swipeTimer = Timer()
            swipeTimer.schedule(object : TimerTask() {
                override fun run() {
                    handler.post(updateUi())
                }
            }, 1000, 2000)
        }
    }

    fun set(runnable : Runnable) {
        Log.d("SyncTimer", "A runner was provided")
        userRunnable = runnable
    }

    private fun updateUi(): Runnable{
        return userRunnable
    }

}

Initialize with
SyncTimer.init()

Pass a runnable
val runnable = Runnable {
    //TODO: Do something
}

The beauty of this code is that you can pass different runnables in different fragments and they'll all work without any new timers being created.
Improve upon this code:

*

*How do you create different timers with different delays and periods?


text:
Q: Is there a way to log which jobs are being worked on when sidekiq is sent SIGTERM? When my sidekiq worker runs out of memory, I don't know what it was working on which caused this. Is there a way to log this? (other than obvious solutions like logging when starting each job).
One idea I have is to catch SIGTERM, something like this:
Sidekiq.configure_server do |config|
  signals = %w[INT TERM]
  signals.each do |signal|
    old_handler = Signal.trap(signal) do

      info = []
      workers = Sidekiq::Workers.new
      workers.each do |_process_id, _thread_id, worker|
        info << work
      end
      ## -> Do something with info <- ##
          ## StatsTracker.count("#{job.name} being processed when shutdown")

      if old_handler.respond_to?(:call)
        old_handler.call
      else
        exit
      end
    end
  end
end


text:
Q: Convert a complicated txt file into a csv file using c# I have absolutely no idea what to do with this but here is a snippet of the file that I'm trying to convert:
"September

3Beef
Lamb Chops

4Fish
Not Fish

5Mac and Cheese
PB & J"

The csv file is supposed to print the date what comes after in quotes, so the above should look like:
Tuesday September Third 2013 "Beef" "Lamb Chops"
Wednesday September Fourth 2013 "Fish" "Not Fish"
Thursday September Fifth 2013 "Mac and Cheese" "PB&J"
Here is what I have so far:
StreamReader reader = new StreamReader(@"..\..\Lunches.txt");

while (!reader.EndOfStream)
{
    string currentLine = reader.ReadLine();
}

StreamWriter writer = new StreamWriter(@"..\..\Lunches.csv");

// date.ToString("ddddd yyyyy mm MMMMMM");
string delimiter = ",";

A:
Here is the code
 private void Form1_Load(object sender, EventArgs e)
    {
        string sayka = "August\n\n" +
            "31Beef\n" +
            "Lamb Chops\n" +

            "24Fish\n" +
            "Not Fish\n" +

            "15Mac and Cheese\n" +
            "PB & J\n";
        MessageBox.Show(makeCSV(sayka));
    }

    string getMonthName(int val)
    {
        switch (val)
        {
            case 1: return "JANUARY";
            case 2: return "FEBRUARY";
            case 3: return "MARCH";
            case 4: return "APRIL";
            case 5: return "MAY";
            case 6: return "JUNE";
            case 7: return "JULY";
            case 8: return "AUGUST";
            case 9: return "SEPTEMBER";
            case 10: return "OCTOBER";
            case 11: return "NOVEMBER";
            case 12: return "DECEMBER";
            default: return null;
        }
    }

    string getDayName(int val)
    {
        switch (val)
        {
            case 1: return "First";
            case 2: return "Second";
            case 3: return "Third";
            case 4: return "Fourth";
            case 5: return "Fifth";
            case 6: return "Sixth";
            case 7: return "Seventh";
            case 8: return "Eighth";
            case 9: return "Nineth";
            case 10: return "Tenth";
            case 11: return "Eleventh";
            case 12: return "Twelth";
            case 13: return "Thirteenth";
            case 14: return "Fouteenth";
            case 15: return "Fifteenth";
            case 16: return "Sixteenth";
            case 17: return "Seventeenth";
            case 18: return "Eighteenth";
            case 19: return "Nineteenth";
            case 20: return "Twentieth";

            default: return "";
        }
    }

    string getDayName2(int val)
    {
        if (val == 30) return "Thirtieth";
        else if (val > 30) return "Thirty " + getDayName(val % 30);
        else if (val > 20) return "Twenty " + getDayName(val % 20);
        else return getDayName(val);
    }

    string makeCSV(string val)
    {
        string res = "";
        string[] ss = val.Split('\n');
        int curMonth = 0;
        for (int i = 0; i < ss.Length; i++)
        {
            if (ss[i].Trim() != "")
            {
                bool isInt = false;
                try
                {
                    int intA = Convert.ToInt32(ss[i][0].ToString());
                    isInt = true;
                }
                catch { }

                if (isInt)
                {
                    bool isDoubleInt = false;
                    try
                    {
                        int intB = Convert.ToInt32(ss[i][1].ToString());
                        isDoubleInt = true;
                    }
                    catch { }

                    int date = 0;
                    if (isDoubleInt) date = Convert.ToInt32(ss[i].Remove(2));
                    else date = Convert.ToInt32(ss[i][0].ToString());

                    DateTime dt = new DateTime(DateTime.Now.Year, curMonth, date);

                    string itemName = "";
                    if (isDoubleInt) itemName = ss[i].Substring(2);
                    else itemName = ss[i].Substring(1);

                    string itemName2 = ss[i + 1];
                    res += dt.DayOfWeek + " " + getMonthName(dt.Month) + " " + getDayName2(dt.Day) + " \"" + itemName + "\"" + " \"" + itemName2 + "\"\n";
                }
                else
                {
                    for (int j = 1; j < 13; j++)
                        if (ss[i].ToUpper().StartsWith(getMonthName(j)))
                        {
                            curMonth = j;
                            break;
                        }
                }
            }
        }
        return res;
    }
}

From the filestream either use StreamReader.readToEnd(), get the string and use the function, Or if the file is big then use it line by line..
Rate if this helps..

A: This is going to be a bit complicated.  I left out some things for you to do.
String[] months = { "January", "February", "March", ....};
Date processDate = new Date();
while (!reader.EndOfStream)
{
    string currentLine = reader.ReadLine();

    // skip this line if blank
    if (String.IsNullOrEmpty(currentLine)) continue;

    if (months.Contains(currentLine)) {
        // we have a new starting month.
        // reset the process date
        Int32 month = DateTime.ParseExact(currentLine.Trim(), "MMMM", CultureInfo.CurrentCulture).Month;
        date = Convert.ToDate(month.ToString() + "/01/2013");
        continue;
    }

    // here's where the real fun begins:
    // you have to pull out the first two characters and test if one or both are digits.
    // This will give you the day.  Put that into your date variable.
    Int32 day = 0;
    char[] arr = currentLine.ToCharArray(0, currentLine.Length);
    if (Char.IsDigit(arr[1])) {
        // first two characters are numbers
        day = Convert.ToInt32(currentLine.Substring(0,2));
        currentLine = currentLine.Remove(0,2);
    } else {
        // only the first character is a number
        day = Convert.ToInt32(currentLine.Substring(0,1));
        currentLine = currentLine.Remove(0,1);
    }

    // set the new date
    date = new DateTime(date.Year, date.Month, day, 0, 0, 0);
    // If we can assume that ALL lines are broken into two parts then we can do the following:
    String secondLine = reader.ReadLine();
    currentLine = String.Format("{0} {1}", currentLine, secondLine);

    // At this point you have the month, day, and the entire line.
    // write it to your lunch stream or store in a StringBuilder
}


text:
Q: How to use Spinner inside AlertDialog.builder? UPDATED:
Hi i'm using spinner within AlertDialog.Builder to show the list of options to select. But the spinner is showing only the first item of the String array when not clicked. If clicked, force close is shown. My code goes below.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater li=LayoutInflater.from(this);
View v=li.inflate(R.layout.searchme, null);
builder.setIcon(android.R.drawable.ic_input_get);
builder.setView(v);

builder.setTitle("Search");
LayoutInflater factory = LayoutInflater.from(getApplicationContext());
final View textEntryView = factory.inflate(R.layout.searchme, null);
builder.setView(textEntryView);
Spinner spin=(Spinner)textEntryView.findViewById(R.id.searchspinner);

    Utilities.ManageDeptSpinner(this, spin);

    for(int i=0;i<spin.getCount();i++)
    {
        long id=spin.getItemIdAtPosition(i);

            spin.setSelection(i, true);
            break;
    }
    spin.setOnItemSelectedListener(new MyOnItemSelectedListener());

    builder.setPositiveButton("Go",new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int id)
        {
            try
            {
                titletext = (EditText) textEntryView.findViewById(R.id.titleText1);
                persontext = (EditText) textEntryView.findViewById(R.id.personText2);
                prioritytext = (EditText) textEntryView.findViewById(R.id.priorityText3);

                title_text = titletext.getText().toString();
                person_text = persontext.getText().toString();
                priority_text = prioritytext.getText().toString();

                String condition = "titlee='"+title_text+"' or pname ='"+person_text+"' or prior='"+priority_text+"'";
                refresh_data(" ASC","prior",condition);
            }
            catch(Exception e)
            {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
            }
    }});

    builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int id)
        {
            dialog.cancel();
                // Do nothing
        }
    });

    AlertDialog alert = builder.create();
    alert.show();

MyOnItemSelectedListener.java :
public class MyOnItemSelectedListener implements OnItemSelectedListener
{
    @SuppressWarnings("unused")
    public void onItemSelected(AdapterView<?> parent,View view, int pos, long id)
    {
    try
        {
        switch(parent.getId())
        {
            case R.id.searchspinner:
                Toast.makeText(getApplicationContext(),"\n Selected : "+parent.getItemAtPosition(pos).toString()+"\n",Toast.LENGTH_LONG).show();
                break;
        }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    public void onNothingSelected(AdapterView<?> parent)
    {
            //  Do nothing.
    }
}

I'm getting exception as follows:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

My output:

If I click on this spinner, Force close is coming.
Any Help is highly appreciated and thanks in advance

A: try using ClassName.this instead of using getApplicationContext() while declaring LayoutInflator.

A: I think you are using a bad context here try to use the right context.
LayoutInflater factory = LayoutInflater.from(getApplicationContext());

instead of using getApplicationContext() try to use Activity_name.this or getParent();

A: before that builder.setView(v); called twice to remove the unwanted one .
Error must be in new MyOnItemSelectedListener() or in xml where you are setting entries .
share code  for both and errorlog as well .


text:
Q: Change name of custom post type archive I have a custom post type acme_reviews. I've namespaced it as suggested in tutorials to prevent future conflicts. But I want its archive page to simply be acme.com/reviews, not acme.com/acme_reviews. How do I achieve this? This is my code:
function create_reviews_post_type() {
    register_post_type('acme_reviews', array(
        'labels' => array(
            'name' => __('Reviews'),
            'singular_name' => __('Review')
            ),
        'menu_position' => 5,
        'public' => true,
        'has_archive' => true,
        )
    );
}
add_action('init', 'create_reviews_post_type');

A: The register_post_type has_archive option also accepts a string. That string will be used for the archives. See the changes in the code below:
function create_reviews_post_type() {
    register_post_type('acme_reviews', array(
        'labels' => array(
            'name' => __('Reviews'),
            'singular_name' => __('Review')
            ),
        'menu_position' => 5,
        'public' => true,
        'has_archive' => 'reviews',
    );
}
add_action('init', 'create_reviews_post_type');

A: According to the codex (and what works for me!) is to just use a rewrite in the array.  Both options work but wordpress suggests using the rewrite Below is the quote directly from the codex:

has_archive
      (boolean or string) (optional) Enables post type archives. Will use $post_type as archive slug by default.
Default: false
Note: Will generate the proper rewrite rules if rewrite is enabled. Also use rewrite to change the slug used.

MAKE SURE TO FLUSH THE PERMALINK RULES.
if this is in a plugin i always suggest adding an init that flushes the rules when the plugin is activated.
Here is the code, notice i customized the function name too for the same reasons that you customize the post name itself.
function create_acme_reviews_post_type() {  //namespaced your function too..
    register_post_type('acme_reviews', array(
        'labels' => array(
            'name' => __('Reviews'),
            'singular_name' => __('Review')
            ),
        'menu_position' => 5,
        'public' => true,
        'has_archive' => true,
        'rewrite' => array( 'slug' => 'reviews' ), //changes permalink structure
        )
    );
}
add_action('init', 'create_acme_reviews_post_type'); //namespaced function call too..


text:
Q: How to render Django model field in template form? I'm trying to add django-faicon field in a form inside my template.
I have a form like:
from faicon.fields import FAIconField

class SomeForm(forms.Form):
    icon = FAIconField()

And I add the field into template:
{{ form.icon }}

But instead a real icon field I see on webpage:
<faicon.fields.FAIconField>

What is a proper way to render icon field outside Django admin?


text:
Q: How to check if list of phrases exists in the text? I have been trying to create a filter that checks if a phrase in a list of phrases exists in the text using recursive functions and match patterns, but somehow that does not seems to work... Maybe someone could give me hint why?
let rec matchTails (tail1 : string list) (tail2 : string list) =
    match tail1, tail2 with
        | h1::t1 , h2::t2 ->
            if (h1=h2) then
                matchTails t1 t2
            else
                false
        | _, [] -> false
        | [],_-> true

let rec check2 (textH: string) (textT: string list) (phrases: string list list) =
    match phrases with
    |[] -> ()
    | h :: t ->
        printfn "%s -- %s" (h.Head) (textH)
        match h with
        |x when x.Length = 1 && x.Head = textH ->
            ()
        |x when x.Head = textH && (matchTails (textT) (x)) ->
            printfn "%s" (x.Head)
        | _ -> ()
        check2 (textH) (textT) (t)

let rec check (phrases : string list list) (text:string list) =
    match text with
    | [] -> ()
    | h :: t ->
        check2 (h) (t) (phrases)
        check phrases t

let p = [["rolex"]; ["free"; "spins"; "everyday"]; ["free"; "cash"]]

let t = ["hello";"and";"welcome";"to";"our";"annual";"free";"cash";"and";"rolex";"giveaway"]

Function call: check p t
I have edited my question with fixing few mistakes, but however, with these lists the program is giving unit() as an output...

A: There are some hints:

*

*matchTails returns incorrect result for
matchTails [ "asdf1" ] [ "asdf" ] => true
matchTails [ "asdf" ] [ "asdf"; "asdf1" ] => true
matchTails [ ] [ "" ] => true

I suspect it should return false in all these cases. Probably the implementation you want is:
let rec matchTails (phrase : string list) (text : string list) =
  match phrase, text with
  | h1 :: t1, h2 :: t2 -> if h1 = h2 then matchTails t1 t2
                          else false
  | [ ], _ -> true
  | _ -> false

let matchTails_test () =
  if not (matchTails [ "" ] [ "" ]) then raise Exception()
  ...

*check2 is not called recursively so only the first phrase is checked

*check is not called recursively, it calls check2 and returns
Generally, try to decompose problem into smaller functions and test each of them separately. You are moving in right direction, what is missing is clarity of what the each of the functions should do and test cases.
Update:
Note that check2 does not really return any value (it returns unit). Also it functionality overlaps with matchTails - it checks the head with the first word in the phrase, it is what matchTails does anyway.
check also returns unit, () means unit.
So let's rewrite check:
let rec check (phrases : string list list) (text : string list) =
  if phrases |> List.exists (fun ph -> matchTails ph text) then
    true
  else
    match text with
    | [] -> false
    | _ :: tail -> check phrases tail

A: While the question has now been basically answered, I would like to point out that its division into sub-problems is already very sufficient; shockingly lacking are the associated testing, and some descriptive naming of the individual functions tackling each sub-problem.
What about naming (and testing) matchTails, check2 and check exemplarily like this?
let ps = [["rolex"]; ["free"; "spins"; "everyday"]; ["free"; "cash"]]
let t = ["hello";"and";"welcome";"to";"our";"annual";"free";"cash";"and";"rolex";"giveaway"]

startsWithPhrase ["hello"; "and"] t
containsPhrase ["free"; "cash"] t
containsAnyPhrase ps t

Spoiler:

 let rec startsWithPhrase phrase text =
    match phrase, text with
    | h1::t1, h2::t2 when h1 = h2 -> startsWithPhrase t1 t2
    | [], _-> true
    | _ -> false

let rec containsPhrase phrase text =
    startsWithPhrase phrase text ||
    match text with
    | _::tl -> containsPhrase phrase tl
    | [] -> false

let rec containsAnyPhrase phrases text =
    match phrases with
    | h::tl ->
        containsPhrase h text ||
        containsAnyPhrase tl text
    | [] -> false

It may be much easier to stay completely with high-level functions, each in place of one recursive loop. Albeit here with a slighty different approach, dividing your haystack into needle-sized slices and comparing each of them with a given phrase.
let containsPhraseHL phrase text =
    Seq.windowed (List.length phrase) text
    |> Seq.exists (Seq.forall2 (=) phrase)

containsPhraseHL ["free"; "cash"] t

let containsAnyPhraseHL phrases text =
    List.exists (fun phrase -> containsPhraseHL phrase text) phrases

containsAnyPhraseHL ps t


text:
Q: How to use setm in puppet I would like to change a one property name ( "modcluster.proxylist" ) with setm Command in Puppet. My following code is not working. Any help is much appreciated.
    augeas { "jboss_domain_config":
            incl    =>      "/opt/domain.xml",
            lens    =>      "Xml.lns",
            context =>      "/files/opt/domain.xml",
            onlyif  =>      "match /files/opt/domain.xml/domain/server-groups/*/system-properties/*/#attribute/name modcluster.proxylist"
            changes =>      "setm /files/opt/domain.xml/domain/server-groups server-group[.]/system-properties/property[.]/#attribute/value kumaran",
    }

Following is my Source XML which i would like to change.
<server-group name="ServiceGroupOne" profile="full-ha">
    <system-properties>
            <property name="jboss.default.multicast.address" value="232.0.2.20" boot-time="true"/>
            <property name="modcluster.proxylist" value="192.168.79.77:7777" boot-time="true"/>
            <property name="modcluster.lbgroup" value="SearchGroupOne" boot-time="true"/>
    </system-properties>
</server-group>
<server-group name="ServiceGroupTwo" profile="full-ha">
    <system-properties>
            <property name="jboss.default.multicast.address" value="232.0.2.20" boot-time="true"/>
            <property name="modcluster.lbgroup" value="SearchGroupTwo" boot-time="true"/>
            <property name="modcluster.proxylist" value="192.168.79.77:7777" boot-time="true"/>
    </system-properties>
</server-group>
<server-group name="ServiceGroupThree" profile="full-ha">
    <system-properties>
            <property name="modcluster.lbgroup" value="CommonSearchGroup" boot-time="true"/>
            <property name="modcluster.proxylist" value="192.168.79.77:7777" boot-time="true"/>
            <property name="jboss.default.multicast.address" value="232.0.2.20" boot-time="true"/>
    </system-properties>
</server-group>

A: There's quite a few problems in there. Let's deal with them one by one:

*

*it seems the domain.xml code you provide is wrong, as there's no domain and server-groups nodes as your Puppet code suggests. I take it there's two more levels around the code you provided:
<domain>
  <server-groups>
    <!-- the rest of the file -->
  <server-groups>
<domain>

*there's no need to set context when using incl and lens, it's automatic

*you misunderstood the way setm works: the first parameter is the nodeset on which Augeas will loop, the second one is the subnode to set and the third one the value

*the change you want to do with setm is inherently idempotent, there's really no need to use onlyif here.

Here's the result:
augeas { "jboss_domain_config":
  incl    =>      "/tmp/domain.xml",
  lens    =>      "Xml.lns",
  changes =>      "setm domain/server-groups/server-group system-properties/property[#attribute/name='modcluster.proxylist']/#attribute/value kumaran",
 }


text:
Q: Modifying Modules path in yii framework I am new to yii framework. I have built Category Moudles using gii tool and I have to enter following URL
http://localhost:8080/myadminpanel/index.php/category/category/create

Here, one category is modules ID and another is Controller ID. How can I made following URL
http://localhost:8080/myadminpanel/index.php/category/create

A: I assume you know where to define routes:
'rules' => array(
    'category/create' => '/category/category/create' // For the "create" action
    'category/<action:w\+>' => '/category/category/<action>' // For all category routes
)