text:
Q: Typescript cannot find name 'Firebase' I get typescript errors when trying to build my project which includes angularfire2 and firebase.  Here are the packages:
"angularfire2": "^2.0.0-beta.0",
"firebase": "^2.4.2",

And here are the errors:
[10:58:34] Finished 'build.html_css' after 4.51 s
[10:58:34] Starting 'build.js.dev'...
c:/Dev/daybreak/node_modules/angularfire2/database/database.d.ts(8,29): error TS2304: Cannot find name 'Firebase'.
c:/Dev/daybreak/node_modules/angularfire2/database/database.d.ts(9,31): error TS2304: Cannot find name 'Firebase'.
c:/Dev/daybreak/node_modules/angularfire2/providers/auth.d.ts(10,25): error TS2304: Cannot find name 'FirebaseCredentials'.
c:/Dev/daybreak/node_modules/angularfire2/providers/auth.d.ts(13,16): error TS2304: Cannot find name 'FirebaseAuthData'.
c:/Dev/daybreak/node_modules/angularfire2/providers/auth.d.ts(14,29): error TS2304: Cannot find name 'FirebaseCredentials'.
c:/Dev/daybreak/node_modules/angularfire2/providers/auth.d.ts(14,59): error TS2304: Cannot find name 'FirebaseAuthData'.
c:/Dev/daybreak/node_modules/angularfire2/providers/auth_backend.d.ts(4,44): error TS2304: Cannot find name 'FirebaseCredentials'.
c:/Dev/daybreak/node_modules/angularfire2/providers/auth_backend.d.ts(8,44): error TS2304: Cannot find name 'FirebaseAuthData'.
c:/Dev/daybreak/node_modules/angularfire2/providers/auth_backend.d.ts(9,25): error TS2304: Cannot find name 'FirebaseAuthData'.
c:/Dev/daybreak/node_modules/angularfire2/providers/auth_backend.d.ts(11,38): error TS2304: Cannot find name 'FirebaseCredentials'.

If I open database.d.ts in node_modules, there is not an import for 'Firebase' so I can see why this would fail..  where is it expecting to get 'Firebase' from?
import { FirebaseListObservable } from '../utils/firebase_list_observable';
import { FirebaseObjectObservable } from '../utils/firebase_object_observable';
import { FirebaseListFactoryOpts } from '../utils/firebase_list_factory';
import { FirebaseObjectFactoryOpts } from '../utils/firebase_object_factory';
export declare class FirebaseDatabase {
    private fbUrl;
    constructor(fbUrl: string);
    list(urlOrRef: string | Firebase, opts?: FirebaseListFactoryOpts): FirebaseListObservable<any[]>;
    object(urlOrRef: string | Firebase, opts?: FirebaseObjectFactoryOpts): FirebaseObjectObservable<any>;
}

I don't get why it's even checking typings in node_modules.. it's part of my exclude in tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "pretty": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitUseStrict": false,
    "noFallthroughCasesInSwitch": true
  },
  "exclude": [
    "node_modules",
    "dist",
    "typings/browser.d.ts",
    "typings/browser",
    "src"
  ],
  "compileOnSave": false
}

A: add this into .ts your file ==> import { AngularFire, FirebaseListObservable } from 'angularfire2';


text:
Q: Making the ToolBar Button Style apply to UserControls in the Toolbar How do I force UserControls in WPF that are inside a ToolBar to use the ToolBar's default button style?
I have a simple user control called ImageButton which has XAML something like this:
<UserControl x:Class="myNameSpace.ImageButtonUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="imageButton"
    >
    <Button Style="{Binding ElementName=imageButton, Path=ButtonStyle}">
        <StackPanel Orientation="Horizontal">
            <Image Source="{Binding ElementName=imageButton, Path=ImageSource}"
                   VerticalAlignment="Center"
                   />
            <TextBlock Text="{Binding ElementName=imageButton, Path=Text}"
                       Style="{Binding ElementName=imageButton, Path=TextStyle}"
                       VerticalAlignment="Center"
                       />
        </StackPanel>
    </Button>
</UserControl>

I have some dependency properties in the code behind for those binding paths and everything works fine.
That is until I put it in a ToolBar. Normally when you put buttons in a ToolBar they are restyled by the ToolBar to look like toolbar buttons. I've found out how I can change this style (see ToolBar.ButtonStyleKey. But how can I apply the already defined style to my User Control's Button Style dependency property?

A: I found a way, that seems to work, although I'm interested in other ways of solving this.
I added a loaded event handler to my UserControl and put this inside it.
if (button.Style == null && this.Parent is ToolBar)
{
    button.Style = (Style)FindResource(ToolBar.ButtonStyleKey);
}

Where button is the name of the button inside my UserControl.

A: Ooh, my apologies!  I misinterpreted your question.  Give this a shot:
<Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}">
    Hello, world!
</Button>

The style only targets buttons, so it can only be applied to buttons. (Which won't be a problem by the look of your comment.)

A: You would require some powerful black magic in order to get it to create a functioning new style for your usercontrol automatically.  There are built-in styles for each type of built-in control that you may add to the toolbar. (Notice that ToolBar.ButtonStyleKey is not alone.) You'll need to craft and apply your own style that matches the standard toolbar elements yourself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Core Data entities faulting when using GCD dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            for (NSDictionary* info in houses) {
                House* house = [DataManager processJSON:info]; //this method processes JSON into Core Data objects and saves them
                [self.data addObject:house];
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                //update the UI based on the new House objects added to the data array

            });

        });

My House objects sometimes work, but often and unpredictably end up like this:
<House: 0x17f8b420> (entity: House; id: 0x17f71e90 <x-coredata://2826DE3A-1762-4958-8402-541D2B1754FA/House/p219> ; data: <fault>)

I believe this has something to do with processing the Core Data objects on a background thread, causing some kind of context conflict. But I can't find many concrete examples of using Core Data with GCD. Any advice on what I can add here to make sure the objects are not faults?

A: In general, you SHALL NOT use some arbitrary queue where you dispatch your Core Data methods which access a particular managed object context and possibly managed objects.
A particular Managed Object Context is associated to either

*

*A dedicated thread (NSConfinementConcurrencyType)

*A private dispatch queue (NSPrivateQueueConcurrencyType)

*The main thread (NSMainQueueConcurrencyType).

If your managed object context is created with the NSConfinementConcurrencyType concurrency policy, you need to remember the thread where you created the context and use this thread to send messages to the context and also send messages to managed objects which are registered with this context.
If the context has been created with the NSMainQueueConcurrencyType concurrency policy, you need to ensure that messages sent to the context and managed objects registered for this context will execute on the main thread.
If the context has been created with NSPrivateQueueConcurrencyType you need to ensure that messages sent to the context and sent to the managed objects registered with this context will execute on this private dispatch queue through using  the managed object context's methods  performBlock: or preformBlockAndWait:.
This is valid for basically all methods - in particular accessing properties of a managed object. There are only a few exceptions, where a method can be executed anywhere irrespective of the concurrency policy, e.g. [NSManagedObject] objectID .


text:
Q: PHP MySQL script gone wrong I'm working on a site and created this experimental script which populates a category menu dynamically based on the database entry.
It worked for a day and then suddenly stopped. I changed my includes for requires and it gave me this error message

Fatal error: Maximum execution time of 30 seconds exceeded in /home1/advertbo/public_html/dev_area/origocloud/include/views/blog/dbget.php on line 34

function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';

$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ado_ocblog", $con);

$htmlString = "";

$result = mysql_query(
    "SELECT *
    FROM subCat
    JOIN headCat ON subCat.headid = headCat.id
    ORDER BY headid ASC;");

$array = mysql_fetch_array($result);
mysql_close($con);

$pre = NULL;
$hc = 0;
$sc = 1;
while ($array) {
    if($pre == NULL){
        $pre = $row["headc"];
        $test[0][0]=$row["headc"];
        $test[0][1]=$row["subc"];

    }
    else
    {
        if($pre ==$row["headc"]){
            $sc++;
            $test[$hc][$sc] = $row["subc"];

        }
        else
        {
            $hc++;
            $sc = 1;
            $test[$hc][0]=$row["headc"];
            $test[$hc][$sc]=$row["subc"];
            $pre = $row["headc"];
        }
    }

}

foreach( $test as $arrays=>$cat)
{
        $first = TRUE;
        foreach($cat as $element)
        {
            if($first == TRUE)
            {
                $htmlString.= '
'.$element.'

                    ';
                $first = FALSE;
            }
            else
            {
                $htmlString.= '
'.$element.'
';
            }

        }
        $htmlString.= '

';
}
return $htmlString;

}

I'm really stuck, the page just keeps timing out the point where i call the function

A: Try this:
while ($array = mysql_fetch_array($result)) {}

Take a look on PHP docs http://php.net/mysql_fetch_array
If does not work, your SQL Query returns too much values and craches the php execution
=]

A: I think it's time to take a step back and look at what you're doing :) This function should do what you want (even if you fixed the infinite loop problem in the function you gave, I don't think it would act how you want it to.):
function getBlogMenu(){
  $dbhost = 'localhost';
  $dbuser = ' ';
  $dbpass = ' ';

  $con = mysql_connect($dbhost, $dbuser, $dbpass);
  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("ado_ocblog", $con);

  $htmlString = "";
  $result = mysql_query(
      "SELECT *
      FROM subCat
      JOIN headCat ON subCat.headid = headCat.id
      ORDER BY headid ASC;");

  // arrays can have strings as keys as well as numbers,
  // and setting $some_array[] = 'value'; (note the empty brackets [])
  // automatically appends 'value' to the end of $some_array,
  // so you don't have to keep track of or increment indexes
  while ($row = mysql_fetch_assoc($result))
  {
    $test[$row["headc"]][] = $row["subc"];
  }

  // don't close the connection until after we're done reading the rows
  mysql_close($con);

  // $test looks like: array('headc1' => array('subc1', 'subc2', 'sub3'), 'headc2' => array('subc4', 'subc5'), ...)
  // so we step through each headc, and within that loop, step through each headc's array of subc's.
  foreach($test as $headc => $subc_array)
  {
    $htmlString.= '
'.$headc.'

';
    foreach($subc_array as $subc)
    {
      $htmlString.= '
'.$subc.'
';
    }
    $htmlString.= '

';
  }

  return $htmlString;
}


text:
Q: how to get pairs of elements via jsoup? Let's say I'm looking for two sibling nodes A and B. They'll satisfy the selector
root.select("A ~ B")

and that selector will return all such Bs.
But what if I need all such A/B pairs? I'm currently doing the following:
root.select("A").stream()
        .filter(a -> a.parent() != null)
        .forEach(a -> {
            Element b = a.parent().select("B:gt(" + a.elementSiblingIndex() + ")").first();
            if (b != null) {
                // do something with a and b
            }
        });

Is this approximately the right idiom? The a.parent().select() seems clunky, but I can't find a simpler way to do it.

A: I don't think there is anything wrong with your approach. If you don't want to use a.parent().select() you could get the same result with siblingElements():
root.select("A~B").stream().forEach(b -> {
    List<Element> siblings = b.siblingElements().subList(0, b.elementSiblingIndex());
    Collections.reverse(siblings);
    for (Element a : siblings) {
        if(a.nodeName().equals(B)) break;
        if(a.nodeName().equals(A)){
            // do something with a and b
        }
    }
});


text:
Q: ElasticSearch and tire/Rails: use two fields for a single facet Using Elasticsearch with Rails 3 and tire gem.
I have got facets to work on a couple of fields, but I now have a special requirement and not sure it is possible.
I have two fields on my model Project that both store the same values: Country1 and Country2
The user is allowed to store up to two countries for a project. The drop down menus on both are the same. Neither field is required.
What I would like is a single facet that 'merges' the values from Country1 and Country2 and would handle clicking on those facets intelligently (i.e. would find it whether it was in 1 or 2)
Here's my model so far: (note Country1/2 can be multiple words)
class Project < ActiveRecord::Base
  mapping do
    indexes :id
    indexes :title, :boost => 100
    indexes :subtitle
    indexes :country1, :type => 'string', :index => 'not_analyzed'
    indexes :country2, :type => 'string', :index => 'not_analyzed'
  end
  def self.search(params)
    tire.search(load: true, page: params[:page], per_page: 10) do
    query do
      boolean do
        must { string params[:query], default_operator: "AND" } if params[:query].present?
        must { term :country1, params[:country] } if params[:country].present?
      end
    end
    sort { by :display_type, "desc" }
    facet "country" do
      terms :country1
    end

  end
end

Any tips greatly appreciated!

A: This commit https://github.com/karmi/tire/commit/730813f in Tire brings support for aggregating over multiple fields in the "terms" facet.
The interface is:
Tire.search('articles-test') do
  query { string 'foo' }
  # Pass fields as an array, not string
  facet('multi') { terms ['bar', 'baz'] }
end

A: according to the elasticsearch docs for the terms facet http://www.elasticsearch.org/guide/reference/api/search/facets/terms-facet.html this should be possible:

Multi Fields:
The term facet can be executed against more than one field, returning
  the aggregation result across those fields. For example:

{
    "query" : {
        "match_all" : {  }
    },
    "facets" : {
        "tag" : {
            "terms" : {
                "fields" : ["tag1", "tag2"],
                "size" : 10
            }
        }
    }
}

did you try providing an array of fields to the term facet like terms :country1, :country2 ?

A: This seems to work but I need to test it more: facet('country') { terms fields: [:country1, :country2]}


text:
Q: Detecting which side touched in openGLES 3dbox in iphone i am working on a project that contains a 3d box that rotated by user touch and opens revelant page when clicked on a side. each side has link to another view so i need to know which side is clicked on the program.
i am using Brad Larson's wonderfull example in my app and i can rotate the cube with touch, thanx to his code and time.
( the code is linked in here: Where to start openGL ES to create and rotate a cube in an iPhone? )
now i need to know how to detect whick side is clicked on the box. normally i develop view based applications, i really have no idea on openGL or things like that.
i've searched the site but couldnt find a good answer (at least something that i can understand with my opengl knowledge)
P.S: Here, the 3dCube code from Brad Larson: http://www.sunsetlakesoftware.com/sites/default/files/CubeExample.zip

A: Take a look here: http://www.3dkingdoms.com/selection.html
In the OpenGL world, I think they refer to this as "picking". The utility function gluunproject will help you. Intersecting the picking ray with your model's faces should not be hard for a cube.


text:
Q: How to download and setup dependencies for a Julia project that is in development? I am trying to download and install dependencies for a Julia project that's not in the package registry. It has a manifest and project file. How do I get all of the packages it depends on to download at once using the Julia Package manager?

A: *

*Download the source: git clone https://github.com/RandomUser/Unregistered.jl

*Activate the project: pkg> activate Unregistered.jl

*Ensure any dependencies are installed: pkg> instantiate
Once the package is set up, you can use the package normally.
You can load the package:
julia> using Unregistered

Or even run its test suite:
pkg> test

A: FWIW, here is a "pure" Julia version of what @David Varela suggested.
After substituting <url-to-project> and /some/local/path this "just works" in the REPL or similar:
using Pkg
Pkg.GitTools.clone("<url-to-project>", "/some/local/path")
cd("/some/local/path")
Pkg.activate(".")
Pkg.instantiate()
# Pkg.precompile() # optional

A: Preparation (optional):

*

*Create a new folder somewhere and cd into it.

*Start Julia with julia --project=.
Now the actual downloading/installing:

*Develop the project locally: pkg> dev --local https://github.com/RandomUser/Unregistered.jl
This will clone the unregistered project into a local subfolder dev/Unregistered and will install all the required dependencies.
If the unregistered project is a Julia package, you can now simply using Unregistered. If you want to work on Unregistered.jl itself you can pkg> activate dev/Unregistered to work in the project environment.


text:
Q: How to get string out of string I have a long string and part of that string is this: 9.26. I want to get 9.26 as a string (using explode?). Thanks for any help. PS: it is html code saved as string.

A: Using preg_match():
$input = 'verylongstring<withother>random</withother>
          tags<9.26';
preg_match('~(.*?)~', $input, $output);
echo $output[1]; // 9.26


text:
Q: Optimizing for-enumerate loop with numba - optimized version is slower I am trying to optimize this function with numba:
@jit(nopython=False, forceobj=True)
def _packing_loop(data: List[str], indices: np.ndarray, strings: List[str], offsets: List[int], str_map: Dict[str, int], acc_len):
    for i, s in enumerate(data):
        # handle null strings.
        if not s:
            indices[i] = -1
            continue

        index = str_map.get(s)
        if index is None:
            # increment the length
            acc_len += len(s)

            # store the string and index
            index = len(strings)
            strings.append(s)
            # strings += s,
            str_map[s] = index

            # write the offset
            offsets.append(acc_len)
            # offsets += acc_len,

        indices[i] = index

The issue is that the optimized code is ~1.5 times slower (even if I pre-run the function once before benchmarking).
What is the possible reason?
I would be also grateful for any suggestions on how to actually optimize this function.
P.S. I am not limited to numba, other approaches are also possible.

A: forceobj generate an inefficient code. To quote the documentation:

If true, forceobj forces the function to be compiled in object mode. Since object mode is slower than nopython mode, this is mostly useful for testing purposes.

You should not use it in production. Besides, Numba do not supports well reflected lists. You should use typed lists for sake of performance. In fact, typing is what makes Numba fast. Without types, Numba cannot generate a compiled code and a slow interpreted version is executed. Note that strings are barely supported and clearly not efficient yet. AFAIK, Numba does not benefit from mypy type annocation like List[str]. I advise you to use Cython in this case. That being said, the speed up will be certainly small since you are dealing mostly with slow CPython dynamic objects.


text:
Q: Restrict domain to Chrome visitors? Possible? Is it possible to restrict a domain to only allow visitors using a specific browser?
I'm building an app and it's only been tested in Chrome so far so I only want to allow Chrome users during Beta testing. Basically, I want to white-list browsers as I go through testing. Any suggestions on the approach I should would be greatly appreciated.

A: Yes you can.
The browser that is accessing the page is in the _SERVER array.
If you find that the accessing browser is not Chrome, then just send a 404 header.

A: You can block all other useragents with a relevant error message using .htaccess
Put this in .htaccess in root of your site:
ErrorDocument 503 "Your must use Chrome to access this site"
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^(Mozilla.*|Safari.*|Other.*)$ [NC]
RewriteRule .* - [R=503,L]


text:
Q: Adding a char to beginning and end of a word in VIM 'Enveloping' a word or a string in a given character is one of my most executed actions in VIM.
Most common char combinations (added at beginning and end, respectively): <>, (), '', "", **, __,--, etc...
Is there a native way of doing this in VIM? If not, how could we set up a macro for this?

A: The most "native" way to surround a word with a given pair of characters is to:

*

*change the word with ciw (the word is put into register " by default),

*insert the opening character,

*insert the content of register " with <C-r>",

*insert the closing character,

*go back to normal mode with <Esc>.

In short:
ciw(<C-r>")<Esc>

This is the most efficient you can get without making custom mappings or installing plugins like Surround or Sandwich.

A: You can create a function abstracting all the chang inner word:
if !exists('*AddSingleQuotes')
    function! AddSingleQuotes()
        exec "normal! ciw''\<Esc>P"
    endfunction
endif
nmap <Leader>q :call AddSingleQuotes()<CR>

And also modify to add double quotes:
if !exists('*AddDoubleQuotes')
    function! AddDoubleQuotes()
        exec "normal! ciw\"\"\<Esc>P"
    endfunction
endif
nmap <Leader>q :call AddDoubleQuotes()<CR>

NOTE: the if !exists part ensures vim will not load the function more than once, even if you reload your vimrc.


text:
Q: 416 Error when creating url from a Blob I'm using the Web Audio API to record a stream of audio source nodes. My code looks like this:
var context,
    bufferLoader,
    destination,
    mediaRecorder,
    source,
    bufferList,
    chunks = [],
    sound_paths = [],
    audioRecordings = [];

//fill in sound paths
sound_paths = ['sound.mp3', 'sound2.mp3'];

bufferLoader = new BufferLoader(
    context,
    sound_paths,
    callback
);

//fill bufferList with bufferdata
bufferLoader.load();

destination = context.CreateMediaStreamDestination();
mediaRecorder = new MediaRecorder(destination);

mediaRecorder.ondataavailable = function(e){
    chunks.push(e.data);
}

mediaRecorder.onstop = function (e) {
    var blob = new Blob(chunks, {'type': 'audio/ogg; codecs=opus'});
    var audio = document.createElement('audio');
    audio.src = URL.createObjectURL(blob);
    audioRecordings.push(audio);

    chunks = [];
};

function startRecording(){
    mediaRecorder.start();
    source = Recorder.context.createBufferSource();
    source.buffer = bufferList[0];
    source.connect(Recorder.destination);
}

function stopRecording(){
    mediaRecorder.stop();
}

//call startRecording(), then source.start(0) on user input
//call stopRecording(), then source.stop(0) on user input

I am using a the BufferLoader as defined here: http://middleearmedia.com/web-audio-api-bufferloader/
This works for the most part, but sometimes I get a 416 (Requested Range Not Satisfiable) when creating a Blob and creating a URL from it. This seems to happen more often when the web page begins to lag. I'm guessing this is because the Blob is undefined when creating the URL, or something like that. Is there a safer way to handle the onstop event for the media recorder? Maybe it would be better to use srcObjet and a MediaStream instead of a Blob?

A: For my website http://gtube.de (just an example no commercial) i am using recorder.js=>https://github.com/mattdiamond/Recorderjs. It works very good. Perhaps you should give that a try to record the context.
If you load the mp3.s in buffers with the web audio api and play them just at the same time it will devinitely work. => https://www.html5rocks.com/en/tutorials/webaudio/intro/
But thats already the way you do it => The code is missing in your example above so i had to read the article => Perhaps next time you try to make a shorter example.
Sorry i don't know enough about mediaStream API => I suppose it's broken ;-)
If something in web-audio doesn't work just try another way. It is still not very stable => Especially the Mozilla people are  supporting it badly.


text:
Q: SBT-compiled package not working properly in Scala REPL I'm developing a Scala package using an sbt project scheme through IntelliJ.  I wanted to use the classes in this package in the Scala REPL, so I followed the instructions in this post.  Namely,

*

*Navigate to where my package's source files are located (MyProject/src/main/scala/mypackage)

*Run "sbt compile"

*Navigate to where sbt stores the compiled source files (MyProject/src/main/scala/mypackage/target/scala-2.12/classes/mytest)

*Run "scala -cp ."

This all works fine until I try to create an instance of one of my package's classes and I get the error MyClass does not have a constructor.  However, if I just paste the class definitions into the Scala REPL, I can create instances with no errors.  What am I doing wrong here?

As a reproducible example, I created a package mytest with two files TraitOne.scala and ClassOne.scala.  The first file looks like
package mytest

trait TraitOne {
  val a: Double
  def aMinus(x: Double): Double = a - x
}

The second file looks like
package mytest

class ClassOne(val a: Double) extends TraitOne {
  def aPlus(x: Double): Double = a + x
}

If I follow steps 1 - 4 as listed above and write val temp = new ClassOne(1.0), I get the error ClassOne does not have a constructor.  But if I paste
trait TraitOne {
  val a: Double
  def aMinus(x: Double): Double = a - x
}
class ClassOne(val a: Double) extends TraitOne {
  def aPlus(x: Double): Double = a + x
}

into the REPL, val temp = new ClassOne(1.0) works fine.

A: Run scala -cp MyProject/src/main/scala/mypackage/target/scala-2.12/classes
Don't include the package in classpath


text:
Q: Is there a word that describes "ranking up a position"? Is there a good word to describe "ranking up a position"?
For example, say a programmer: A junior programmer _____s into a senior programmer....
Ranks up doesn't sound that good, and I'm looking for a single word (if any exists).

A: Going up the ranks in a professional (workplace) environment is typically known as a promotion.

Andy got promoted to senior management yesterday.
I'm hoping to get promoted to vice president soon.

However a promotion is usually used to show advancement in a specific job or workplace. There are other terms which imply more general career advancements through one's professional career.
A junior programmer having achieved 5 years of experience is usually ranked up or receives the title of senior programmer. This title/rank is independent of a specific position at a company which is why you see many job postings looking to hire a senior programmer or senior developer (implying the title senior can be independent of a current job title at a specific company).
Side Note: In the field of computer science there are also other ranks that can only be achieved through experience. For example when a company is looking for a Software Architect they are not trying to find people who majored in software architecture (such a major rarely exists). What they are looking for (usually) is a software engineer with 10+ years of experience. In short, there are certain titles which are not entry-level (meaning you can not earn a degree and automatically earn that title) which don't necessarily start with senior or junior but are achieved through a similar process.

A: If you are looking for a word to accompany the act of moving into the more senior position, then the already-suggested promotion is quite adequate.
If, however, you are looking for a word that describes the process of gaining the skills and experience, then mature might be a better word:

: to become fully developed in the body and mind
  : to continue developing to a desired level
source: www.m-w.com/dictionary/mature

(Alternatively, as that definition suggests, develop could also be suitable.)


text:
Q: Advice On Technologies Used For Online Payment Sites I would like to create a site along similar lines to justgiving.com, uk.virginmoneygiving.com etc.
In principle, it seems easy enough

*

*Organisation enters their bank details on my site

*Customer chooses organisation form a list

*Customer uses CC to make payment to organisation

*Money goes into central account (holding area)

*At a specified time, money gets transferred to organisation

I would like to give the customer the choice of storing their CC details on my site (more flexible for them) or not (more secure for them)
I was also thinking of making it an open app so that other businesses, through the use of an API, could use my banking system.
I'm more than aware of the cost involved in developing something like this (I'm not wet behind the ears)
Is there an easy middle ground to get up and running (use third parties) until I get the experience to develop my own system?
Could this be an off the shelf purchase or would I have to develop it bespoke (myslef or get an external company to do it)?
What sort of technologies would be involved?
Anything I've missed? I really don't know the terminology for what I want to do so my Googling has proved fuitless.
Who can point me in the right direction of good docs so I can learn the terminology/technology.
Thank you.

A: Your best and most secure option is to check out providers for this.
Their system can be integrated seamlessly in you site.
Do a google search and you'll find lots.
Take a look at paypal, Ogone etc.

A: I can recommend Quantiv, they can provide a simple, modern payment back-end and they're quite affordable.


text:
Q: How to place a div centered inside a other div (Just a smaller rectangle inside a big one)? I'm trying to center all the "boxes" inside the boxes. It should be also maintain measures when I'm changing the window size. I'm also trying to distribute the yellow boxes equally inside the purple one.
I tried to different CSS alignments but failed it getting a solid structure.
I want especially the purple box with yellow boxes centered in the green box.
Thanks for your tips!

.wrapper {
  display: grid;
  border-style: solid;
  border-color: red;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  width: 99%;
  margin-left: 0.25%;
  height: 98vh;

}
.buildground {
  display: grid;
  border: 1px solid;
  border-color: purple;
  grid-template-columns: repeat(10, 1fr);
  grid-template-rows: repeat(3, 1fr);
  width: 80%;
  height: 80%;

}

.ground-item{
  border: 1px solid orange;
  width: 100%;
  height: 100%;

}

.buildarea {

  border: 1px solid green;
  margin: 10px;
  justify-content: space-around

}

.two{
  border: 1px solid blue;
  margin: 10px;
  padding: 10px;

}
.three{
  border: 1px solid blue;
  margin: 10px;
  padding: 10px;

}
.four{
  border: 1px solid blue;
  margin: 10px;
  padding: 10px;

}

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

Two

Three

Four

A: Add flexbox to designarea to center horizonatally and align-self:center to .buildground

.wrapper {
  display: grid;
  border-style: solid;
  border-color: red;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  width: 99%;
  margin-left: 0.25%;
  height: 98vh;
}

.buildground {
  display: grid;
  border: 1px solid;
  border-color: purple;
  grid-template-columns: repeat(10, 1fr);
  grid-template-rows: repeat(3, 1fr);
  width: 80%;
  height: 80%;
  align-self: center;
  /* this */
}

.ground-item {
  border: 1px solid orange;
}

.buildarea {
  display: flex;
  /* this */
  border: 1px solid green;
  margin: 10px;
  justify-content: space-around;
}

.two {
  border: 1px solid blue;
  margin: 10px;
  padding: 10px;
}

.three {
  border: 1px solid blue;
  margin: 10px;
  padding: 10px;
}

.four {
  border: 1px solid blue;
  margin: 10px;
  padding: 10px;
}

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

1

Two

Three

Four


text:
Q: Facebook payments, currency, symbols and formatting Going through all the Facebook documentation it would appear there's no way to say to the Facebook SDK "Give me the price string I need to display to the local user for product x".
I'm struggling to believe this is truly the case, as surely this is a basic must have for a company offering an SDK for international purchases.
My question is, is there really no way to get this information from Facebook? They clearly can get it themselves as they display it in their payment dialog. Why do they not provide it to the developer?
If it really is impossible to get the information from Facebook, then how would you recommend I go about dealing with this to display a relevant price to the user.


text:
Q: .addClass using else if statements - jQuery? I'm very new to JavaScript and jQuery. I want to make the white button at the top change color after these list of colors is pressed. For example, when the pink button is pressed, the white button turns pink, and then when the purple button is pressed, it changes to purple:
https://i.stack.imgur.com/q4zA0.png

I've managed to get it to work when the pink button is pressed using this function that selects the ids of the li element and the .addClass() method.
//When clicking diff colours
$("ul").on("click", "li", function(){
    if ($("li").is("#p")) {
        $("button").addClass("pink");
    } else if ($("li").is("#pu")) {
        $("button").addClass("purple");
    }
    color = $(this).css("background-color");
});

However, using else if doesn't seem to work when, for example, pressing the purple button.
Here is the HTML snippet:

A:

//When clicking diff colours
$("ul").on("click", "li", function() {
  $("button").removeAttr('class').addClass($(this).attr('class'))
});
.white {
  background-color: white
}
.pink {
  background-color: pink
}
.purple {
  background-color: purple
}
.red {
  background-color: red
}
.blue {
  background-color: blue
}
.green {
  background-color: green
}
.orange {
  background-color: orange
}

pink

purple

red

blue

green

orange

<button>button</button>

Assuming the li has only one class

A: The result is expected as $('li').is("#p") will always evaluate to true as it will evaluate against all li element not the current element.
You need to use current element context i.e. this instead of li when evaluating it.
//When clicking diff colours
$("ul").on("click", "li", function(){
    if ($(this).is("#p")) {
        $("button").addClass("pink");
    } else if (this).is("#pu")) {
        $("button").addClass("purple");
    }
    color = $(this).css("background-color");
});

It would be better to use ID
//When clicking diff colours
$("ul").on("click", "li", function(){
    if (this.id == "p") {
        $("button").addClass("pink");
    } else if (this.id == "pu") {
        $("button").addClass("purple");
    }
    color = $(this).css("background-color");
});

A: That's because you always refer to the first li instead of the pressed one:
$("ul").on("click", "li", function(){
    if ($(this).is("#p")) {
        $("button").addClass("pink");
    } else if ($(this).is("#pu")) {
        $("button").addClass("purple");
    }
    color = $(this).css("background-color");
});

A: To solve this you can make the code simpler by applying the class of the clicked element directly to the <button>. This avoids the need for the if statement at all. Try this:

//When clicking diff colours
$("ul").on("click", "li", function() {
  $('button').removeClass().addClass(this.className);
});
button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 0;
}
.pink { background-color: pink; }
.purple { background-color: purple; }
.red { background-color: red; }
.blue { background-color: blue; }
.green { background-color: green; }
.orange { background-color: orange; }

<button></button>


text:
Q: JCheckbox display a displayName but save a different value behind the scenes I have a JCheckbox to define the name of a person:
JCheckBox j = new JCheckBox("displayName");

But I need that whenever this checkbox is selected "ActualName" is user for processing in the code, but only "displayName" be displayed.
Is it possible to display a different value and save a different value at the backend?

A: Examine tutorial for JCheckBox.
You need to use ItemListener for your logic.

A: Take any local variable i.e int, String or anything you want as following.
here I will take int a as value.
    JCheckBox j = new JCheckBox();
    j.setText("Display Name");

After Submitting your form in action listner write following code
    int a;
    boolean temp=j.isSelected();
    if(temp)
    {
        a=111;
        //if JCheckBox is selected set value
    }
    else
    {
       a=222;
       //if JCheckBox is NOT selected set value
    }


text:
Q: Maximum Likelihood estimation of $~~~\theta~ x^{\theta -1}$ Determine the maximum likelihood estimator $\hat \theta$ from $\theta$. If $X_i\, , \quad i=1,\, 2,\, \ldots ,\, n$
Given function :
$$f(x)=\begin{cases} \theta x^{\theta -1}\,\quad ,\,0\lt x \lt 1\, ; \, 0\le \theta \le \infty\\~~~~ 0\qquad,\text{ for other }x\end{cases}$$
My answer :
$\begin{aligned}
L(\theta\, ; \, x_i)&=\theta x_1^{\theta -1}\cdot \theta x_2^{\theta -1}\cdots \theta x_n^{\theta -1}\\
&= \displaystyle\prod_{i=1}^n \theta x_i^{\theta -1}\\
\ln{L(\theta\, ; \, x_i)}&=\ln{\displaystyle\prod_{i=1}^n \theta x_i^{\theta -1}}\\
&= \displaystyle\sum_{i=1}^n \ln{\theta x_i^{\theta -1}}\\
&= \displaystyle\sum_{i=1}^n \ln{\theta}+ \displaystyle\sum_{i=1}^n \theta \ln{x_i}- \displaystyle\sum_{i=1}^n \ln{x_i}\\
&=n\cdot \ln{\theta}+ \displaystyle\sum_{i=1}^n \theta \ln{x_i}- \displaystyle\sum_{i=1}^n \ln{x_i}\\
\dfrac{\partial \ln{L(\theta\, ; \, x_i)}}{\partial \theta}&= \dfrac{n}{\theta}+\displaystyle\sum_{i=1}^n \ln{x_i}=0\\
\hat \theta &= \dfrac{-n}{\displaystyle\sum_{i=1}^n \ln{x_i}}
\end{aligned}$
I doubt my answer. Please gimme some corrections if anything is wrong. And tell me which one. Thanks.

A: Why do you doubt your answer?  It is for the most part correct.
Recall here that the support of $X$ is the open interval $(0,1)$.  Therefore, $\log x_i \in (-\infty, 0)$, hence $\hat \theta \in (0,\infty)$.  It may be instructive to use a computer to generate some realizations of $X$ and calculate the MLE from the sample.  I generated $n = 100$ such realizations:

0.423195, 0.904185, 0.768371, 0.709028, 0.82171, 0.98423, 0.833026,
  0.967757, 0.831291, 0.942482, 0.804875, 0.936858, 0.703554, 0.924037,
  0.910317, 0.889744, 0.964979, 0.937217, 0.959913, 0.901902, 0.941537,
  0.847308, 0.987343, 0.824175, 0.766928, 0.649205, 0.996147, 0.870595,
  0.923796, 0.818284, 0.779518, 0.914382, 0.996359, 0.904565, 0.821205,
  0.936537, 0.926851, 0.907287, 0.916814, 0.754686, 0.422209, 0.977708,
  0.885583, 0.913659, 0.72229, 0.932748, 0.786656, 0.9677, 0.6759,
  0.939519, 0.939619, 0.976682, 0.901609, 0.877578, 0.957474, 0.659596,
  0.812173, 0.77898, 0.93857, 0.846139, 0.970211, 0.991469, 0.941998,
  0.99228, 0.941368, 0.919001, 0.877389, 0.964053, 0.62892, 0.974418,
  0.836646, 0.747614, 0.994126, 0.784671, 0.886119, 0.957653, 0.723802,
  0.763465, 0.849859, 0.972564, 0.818141, 0.864318, 0.955251, 0.994557,
  0.999883, 0.84261, 0.792689, 0.976037, 0.378906, 0.854057, 0.881663,
  0.962214, 0.882605, 0.633129, 0.979769, 0.984534, 0.972508, 0.934276,
  0.970884, 0.687226

What is your MLE for this sample?  Can you calculate the variance of this estimator; i.e., what is $\operatorname{Var}[\hat \theta]$?


text:
Q: If a logging warning occurs before __main__, how is it being called? I'm working on a corporate python program which uses buck build. When I run part of the program, abc.py (via a .par file), then it runs the program starting with if __name__ == "__main__" etc.
However, I'm trying to find source of logging warnings that occur before any of the contents of the if __name__ ... are run. Or perhaps keywords to understand this better. What could be running before the main file?

A: Your mistake is thinking execution starts with if __name__ == "__main__":. That check is a guard that prevents the guarded code from executing when imported as a module, rather than run as the main script. The unguarded code always runs, regardless of how the module is loaded, so if the guard is at the bottom of the file, the rest of the file is run before it is reached.
So if you have a module:
# foo.py
print("foo")

And a script:
# main.py
import foo

def main():
    print("Main")

if __name__ == '__main__':
    main()

and you run python3 main.py, execution of main.py begins with import foo, which ends up printing foo immediately. Then main.py defines the main function (defining functions without calling them is still executing code; if Python had skipped to the guarded code, main wouldn't exist), then the guard is checked, the check passes, and main is called. Basically every bit of top-level code (typically imports, global constants, functions, and class definitions) is executed before the guarded block is reached; normally that top-level code does nothing visible, but if an imported module tried to do some real work and logged during the process, it would take effect before you ever reached your guarded "main script" code.


text:
Q: Fragment with drawermenu in action toolbar The problem is the following I have my main activiy that consists of a drawer activity when I give some of the options of the drawer activity I have to pass to a fragment, the problem is the following when I pass to the fragment I lose the option to open the menu From the drawer from the fragment
`
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }
@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);`

This is the main activity java code
This is the fragment code where I want to implement the drawer
public class Fragmen1 extends Fragment {

   Button HBoton;
   Button GBoton;
   Button SCTBoton ;
   Button RGboton ;
   Button CPBoton ;
   Button ARBoton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fragmen1, container, false);

        HBoton = (Button) view.findViewById(R.id.HipotenusaBoton);
        HBoton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent HBoton = new Intent(getActivity(), Hipotenusa.class);
                startActivity(HBoton);
            }
        });

         GBoton= (Button) view.findViewById(R.id.button3);
        GBoton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent GBoton = new Intent(getActivity(), Grados_Radianes.class);
                startActivity(GBoton);
            }
        });

        SCTBoton = (Button) view.findViewById(R.id.SCTboton);
        SCTBoton.setOnClickListener(new  View.OnClickListener() {

            @Override
            public  void  onClick (View v ){

                Intent SCTBoton = new Intent(getActivity(), SenoCosenoTangente.class);
                startActivity(SCTBoton);
            }
        });

        RGboton = (Button) view.findViewById(R.id.button6);
        RGboton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent RGboton = new Intent(getActivity(),RadianesGrados.class);
                startActivity(RGboton);
            }
        });

        CPBoton = (Button) view.findViewById(R.id.CAPbutton);
        CPBoton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent CPBoton = new Intent( getActivity(),CordenadasRectagularesPolares.class);
                startActivity(CPBoton);
            }
        });

        ARBoton = (Button) view.findViewById(R.id.arboton);
        ARBoton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent ARBoton = new Intent( getActivity(),AnguloReferencia.class);
                startActivity(ARBoton);

            }
        });

        return  view;

    }

}


text:
Q: Wait without blocking thread? - How? This is probably one of the most elementary things in F#, but I've just realized I've got no idea what's going on behind the sceens.
let testMe() =
    async { printfn "before!"
            do! myAsyncFunction() // Waits without blocking thread
            printfn "after!" }

testMe |> Async.RunSynchronously

What's happening at do! myAsyncFunction()? I'm aware of that it waits for myAsyncFunction to finish, before moving on. But how can it do that, without blocking the thread?
My best guess is that everything after do! myAsyncFunction() is passed along as a continuation, which gets executed on the same thread myAsyncFunction() was scheduled on, once myAsyncFunction() has finished executing.. but then again, that's just a guess.

A: As you correctly pointed out, the myAsyncFunction is passed a continuation and it calls it to resume the rest of the asynchronous workflow when it completes.
You can understand it better by looking at the desugared version of the code:
let testMe() =
  async.Delay(fun () ->
    printfn "before!"
    async.Bind(myAsyncFunction(), fun () ->
        printfn "after!"
        async.Zero()))

They key thing is that the asynchronous workflow created by myAsyncFunction is given to the Bind operation that starts it and gives it the second argument (a continuation) as a function to call when the workflow completes. If you simplify a lot, then an asynchronous workflow could be defined like this:
type MyAsync<'T> = (('T -> unit) * (exn -> unit)) -> unit

So, an asynchronous workflow is just a function that takes some continuations as argument. When it gets the continuations, it does something (i.e. create a timer or start I/O) and then it eventually calls these continuations. The question "On which thread are the continuations called?" is an interesting one - in a simple model, it depends on the MyAsync that you're starting - it may decide to run them anywhere it wants (i.e. Async.SwithcToNewThread runs them on a new thread). The F# library includes some additional handling that makes GUI programming using workflows easier.
Your example uses Async.RunImmediate, which blocks the current thread, but you could also use Async.Start, which just starts the workflow and ignores the result when it is produced. The implementation of Async.Start could look like this:
let Start (async:MyAsync<unit>) = async (ignore, ignore)


text:
Q: How can I execute a child python scriptby clicking on a button on a parent script? I am currently training OOP for GUI. I am using the wxPython library to create my windows and customize them.
Right now, I am trying to launch a python script by clicking on a button from an other script.
For that, I have 2 programs, wx_Practicing.py and wx_Practicing_child.py which are in the same folder.
wx_Practicing.py
import wx
import time
import wx_Practicing_child
import threading
import os
import sys

class MainWindow(wx.Frame):
    def __init__(self):
         wx.Frame.__init__(self, None, wx.ID_ANY, "Test",
         wx.DefaultPosition,(1000,850), wx.DEFAULT_FRAME_STYLE, wx.FrameNameStr)

    # Click counter and flag variable for the new frame opened
    self.click = 0
    self.OpenButtonFlag = 0

    # Sizer to definit the position of elements
    sizer_hori = wx.BoxSizer(wx.HORIZONTAL)
    sizer_verti = wx.BoxSizer(wx.VERTICAL)

    # Panel
    test_panel = PanelMainWindow(self)
    test_panel.SetSizer(sizer_verti)

    # Button to close the main frame and end the program
    btn_quit = wx.Button(test_panel, label ="Quit")
    btn_quit.Bind(wx.EVT_BUTTON, self.OnQuit)
    sizer_verti.Add(btn_quit)

    # Button which displays the number of click done on it since the
    # frame is opened
    btn_counter = wx.Button(test_panel, label="Click counter")
    sizer_verti.Add(btn_counter)
    btn_counter.Bind(wx.EVT_LEFT_DOWN, self.OnCount)

    # Button which open the child frame from wx_Practicing_child.py
    btn_new_frame = wx.Button(test_panel, label = "Open new frame")
    sizer_verti.Add(btn_new_frame)
    btn_new_frame.Bind(wx.EVT_LEFT_DOWN, self.OnNewFrame)

    self.Show()

# Method to quit the frame and close it
def OnQuit(self, event):
    self.Close()

#Method to count clicks
def OnCount(self, event):
    self.click +=1
    print(self.click)

# MEthod which open the child frame
def OnNewFrame(self, event):
    if self.OpenButtonFlag == 0 :
        print('aaaaaaaa')
        os.system('wx_Practicing_child.py')
        self.Show()
        print("New frame opened")
        self.OpenButtonFlag = 1
    else :
        print("Frame already launched, close it before opening a new one")

class PanelMainWindow(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

test = wx.App(False)
frame = MainWindow()

test.MainLoop()

wx_Practicing_child.py
import wx
class MainWindow_child(wx.Frame):
    def __init__(self):
          wx.Frame.__init__(self, None, wx.ID_ANY, "Test",
          wx.DefaultPosition, (1000,850), wx.DEFAULT_FRAME_STYLE, wx.FrameNameStr)

    self.OpenButtonFlag = 0

    # Sizer
    sizer_hori = wx.BoxSizer(wx.HORIZONTAL)
    sizer_verti = wx.BoxSizer(wx.VERTICAL)

    # Panel
    test_panel_child = PanelMainWindow_child(self)
    test_panel_child.SetSizer(sizer_verti)

    # Button to quit the child frame
    btn_quit = wx.Button(test_panel_child, label ="Quit")
    btn_quit.Bind(wx.EVT_BUTTON, self.OnQuit)
    sizer_verti.Add(btn_quit)

    self.Show()

# Method used to close the child frame
def OnQuit(self, event):
    self.OpenButtonFlag = 0
    self.Close()

class PanelMainWindow_child(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

So basically, the functionning is simple. I launch wx_Practicing.py to open the parent window, then I click on the "Open new frame" button and the child frame from wx_Practicing_child.py appears. If i trigger the button again, it does nothing until I closed the previous child window.
But when I try it, the buttonFlag is set to 1, so it enters in the loop, but the child frame does not appear.
So I would like to know how could I make it work. I am out of option right now.
Thank you.

A: Welcome to StackOverflow.
The problem is that you are creating the child frame in the wrong way.
You only need to change the line:
os.system('wx_Practicing_child.py')

for:
child = wx_Practicing_child.MainWindow_child()


text:
Q: How to make razor not read @ How to make razor not read @ at input pattern?
<input type="email" class="form-control" id="email" name="Email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{1,}$" title="Email must be in correct fomat" value="" placeholder="Email"   required />

A: Using a double at would work: @@.
Alternatively you could use this razor function: @Html.Raw("@").


text:
Q: get css value on media query change via enquire.js enquire

  .register('screen and (min-width: 1200px)', {

    match: function() {

      active_li_margin_left = $('li.active').css('margin-left')
      active_li_width = $('li.active').width()

      console.log(active_li_margin_left, active_li_width)

      zwarovsky();

    }

  })

  .register('screen and (min-width: 980px) and (max-width: 1199px)', {

    match: function() {

      active_li_margin_left = $('li.active').css('margin-left')
      active_li_width = $('li.active').width()

      console.log(active_li_margin_left, active_li_width)

      zwarovsky();

    }

  })

li.active width change from 770px to 620px, where margin-left from -30px to -20px, this are bootstrap span8 items.
the problem:
seems that enquire fire the functions just before the css media query, so it pickup the previous values when you resize the window.
when i switch from 1200 to 980 resizing the browser window console log show 30px 770 instead 20px 660, and than when i switch back from 980 to 1200 console log show 20px 620.


text:
Q: chekbox always checking last item in recyclerview i want to get item from checked checkbox in my recyclerview item, this my adapter
class SelectedListDateAdapter(var listDate: List<DateDay>, private val onItemCheckListener: OnItemCheckListener) :
RecyclerView.Adapter<SelectedListDateAdapter.SelectedListDateViewHolder>() {
lateinit var  binding: ItemCheckBoxDateBinding
inner class SelectedListDateViewHolder(item: ItemCheckBoxDateBinding) : RecyclerView.ViewHolder(item.root) {
    val checkBoxList = item.checkBox
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SelectedListDateViewHolder {
    binding = ItemCheckBoxDateBinding.inflate(
        LayoutInflater.from(parent.context),
        parent,
        false
    )
    return SelectedListDateViewHolder(binding)
}

override fun onBindViewHolder(holder: SelectedListDateViewHolder, position: Int) {
    holder.checkBoxList.setOnCheckedChangeListener(null)
    holder.checkBoxList.isChecked = listDate[position].isSelected
    holder.itemView.apply {
        val currentItem = listDate[position]
        binding.tvDateList.text = listDate[position].date

        setOnClickListener {
            binding.checkBox.isChecked = !binding.checkBox.isChecked
            if (binding.checkBox.isChecked) {
                binding.checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
                    currentItem.isSelected = isChecked
                }
                onItemCheckListener.onItemCheck(currentItem)
            } else {
                binding.checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
                    currentItem.isSelected = isChecked
                }
                onItemCheckListener.onItemUncheck(currentItem)
            }
        }
    }
}

override fun getItemCount(): Int {
    return listDate.size
}

}
im referring to this question get list of checked item to make that adapter
yes, it get the item and remove them but everytime i click an item in recyclerview it always check and uncheck the last item
i have checking this question CheckBox in RecyclerView keeps on checking different items but my result still the same, any help is appreciated

A: Maybe viewHolder reuse the previous item.Try to update listData, not currentItem.
And move the nested Listener
override fun onBindViewHolder(holder: SelectedListDateViewHolder, position: Int) {

    holder.itemView.tvDateList.text = listDate[position].date
    holder.checkBoxList.isChecked = listDate[position].isChecked
    holder.checkBoxList.setOnClickListener {

       listDate[position].isSelected = holder.checkBoxList.isChecked
    }

    holder.itemView.setOnClickListener {

        holder.checkBoxList.isChecked = !holder.checkBoxList.isChecked
        listDate[position].isSelected = holder.checkBoxList.isChecked

        val currentItem = listDate[position]
        if (holder.checkBoxList.isChecked) {

            onItemCheckListener.onItemCheck(currentItem)

        } else {

            onItemCheckListener.onItemUncheck(currentItem)
        }
    }
}


text:
Q: MVC Jquery Dialog Box not appearing on POST I am using MVC C# with Jquery Dialog. When I do a POST, I am redirected to a normal page vs
the dialog box.
Here is what my code looks like:
inside View:

Within my click event I have the following:
      $('#dialog').dialog({
                   autoOpen: false,
                   width: 500,
                   resizable: true,
                   title: 'PVT Report',
                   modal: true,
                   buttons: {
                       "Close": function () {
                       $(this).dialog("close");
                        }
                      }
                  });

       $('#dialog').dialog('open');

                 $.ajax({
                           url: url,
                           type: 'GET',
                           success: function(result) {

                           if (result.success)
                           {
                             $('#dialog').dialog('close');
                          }
                           else
                           {
                              $('#dialog').html(result);
                           }
                         }
                  });
                 }

It goes to the url just fine and displays the dialog box.
When I do a POST, it did does not go back to the dialog box but instead goes to a regular page:
Below are my GET and POST:
     public ActionResult FileUpload(int id)
     {
        var model = new FileUpload { PlNum = id}
        return PartialView(model);
     }

    [HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase file, FileUpload model)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0)
        {
            // extract only the fielname
            var fileName = Path.GetFileName(file.FileName);
            string extension = Path.GetExtension(file.FileName);

            if (extension != ".pdf")
            {
                TempData["ErrMessage"] = "Error, wrong file type. File must be a PDF file.";
                return RedirectToAction("FileUpload", new { id = model.PlNum });
            }

.....
Here is my View:
@using (Html.BeginForm("FileUpload", "Plt", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
       @Html.HiddenFor(a => a.PlNum)

File upload for Pl# @Model.PlNum

       <input type="file" name="file" />
       <input type="submit" value="OK" />
}

I thought doing it with $.ajax would be fine. I think one of my issue is that when I do a redirecttoAction, the dialog box is no longer
open..
Note that in either way, if successful or if not successful, I like to return back to the dialog box. If successful, there will be a message that says "Successful". If not successful, there will be an error message.

A: Just to make sure that I have correctly understood your question, please allow me to first restate your goals before answering. Please correct me if I am wrong.

*

*You want to display some partial view containing a form inside a jQuery UI dialog

*This form contains a file upload input which would allow for the user to select and upload a file to the server from his computer

*You want this upload to happen asynchronously using AJAX

*If the upload succeeds you want to thank the user for having uploaded the file and close the jQuery dialog

*If there's an error during the request you want to display an error message to the user. For example if he didn't select any file even if this field was required

If I didn't understand some of your your goals, you could stop reading my answer and update your question to provide more information about what exactly are you trying to achieve.
The challenge here consists in uploading a file with an AJAX request. As you know this is not possible with standard techniques. There are many workarounds though. You could use a plugin such as Uploadify or FineUploader or use the new HTML5 File API which allows you to achieve that and which is supported by all modern browsers (no, IE9 is not a modern browser, sorry). I will cover the lats option because we are in 2013 and we all use modern browsers and nobody gives a ... about IE.
So as in every ASP.NET MVC application we could start by designing a view model which will meet the requirements of our view and the information we would like to have in the upload form:
public class MyViewModel
{
    public int Id { get; set; }

    [Required]
    public HttpPostedFileBase File { get; set; }
}

Then we could have a controller that will handle the process:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Upload(int id)
    {
        var model = new MyViewModel
        {
            Id = id
        };
        return PartialView(model);
    }

    [HttpPost]
    public ActionResult Upload(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // There was a validation error, probably the user didn't select any file
            // we set the status code to 400 (BadRequest) and return the
            // same partial which will contain the validation error
            Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
            return PartialView(model);
        }

        // at this stage we know that the model is valid =>
        // we could process the uploaded file. In this particular example
        // I am saving the uploaded file to the App_Data folder on the server
        // and ignoring the Id parameter of the view model. Obviously
        // in a more real world application here you might want to store the
        // physical location of this file in your data store as well as it's MIME type
        // so that you could display it later
        var file = Path.Combine(
            Server.MapPath("~/App_Data"),
            Path.GetFileName(model.File.FileName)
        );
        model.File.SaveAs(file);

        // we have finished => let's set the response status code to
        // 204 (NoContent) so that the client side javascript that I will show
        // later in my answer could distinguish this case from the error scenario
        Response.StatusCode = (int)System.Net.HttpStatusCode.NoContent;

        // we will return an EmptyResult because in this particular example
        // I don't really care about returning some information to the client
        // from the server. If you care you could of course set the status code
        // to 200 (Success) and return, say, a JsonResult here
        return new EmptyResult();
    }
}

Not much to be said about this controller. Pretty standard stuff. An Index action to serve some dummy view that will contain a link to initiate the upload process. An Upload (GET) action to serve the upload form partial and of course an Upload (POST) action to handle the actual file upload (in this oversimplified example I am storing the file on the server).
Then we could have the corresponding ~/Views/Home/Index.cshtml dummy view:
@model MyViewModel
@Html.ActionLink(
    "click here to upload a file",
    "Upload",
    new { id = 154 },
    new { id = "uploadLink" }
)

Easy: a strongly typed view containing an anchor that will subsequently (see later in my answer) be AJAXified in order to show the upload partial inside a jQuery dialog and a div placeholder for the dialog.
Next we could write the upload partial that will contain the form (~/Views/Home/Upload.cshtml):
@model MyViewModel

@using (Html.BeginForm(null, null, new { id = Model.Id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{

        @Html.LabelFor(x => x.File)
        @Html.TextBoxFor(x => x.File, new { type = "file" })
        @Html.ValidationMessageFor(x => x.File)

    <button type="submit">Upload</button>
}

Once again, pretty standard stuff here => an HTML form containing a file input that will allow the user to select a file to be uploaded.
And the final step of course is the javascript that will make all this come alive. You could put this javascript in a Scripts section inside your Index view that you overrode from the _Layout. Ideally scripts should be placed at the end of the document, before the closing  tag (that's the reason why I am not wrapping the .click() handler subscription in a document.ready):
$('#uploadLink').click(function () {
    $.ajax({
        url: this.href,
        type: 'GET',
        cache: false,
        success: function (result) {
            $('#dialog').html(result).dialog({
                autoOpen: true,
                width: 500,
                resizable: true,
                title: 'PVT Report',
                modal: true,
                buttons: {
                    'Close': function () {
                        $(this).dialog("close");
                    }
                }
            });
        }
    });
    return false;
});

$('#dialog').on('submit', 'form', function () {
    var xhr = new XMLHttpRequest();
    xhr.open(this.method, this.action);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 204) {
                // upload was successful => thank the user and close
                // the dialog
                alert('Thank you for uploading the file');
                $('#dialog').dialog('close');
            } else if (xhr.status == 400) {
                // validation error occurred on the server => redisplay the form
                $('#dialog').html(xhr.responseText);
            }
        }
    };
    xhr.send(new FormData(this));
    return false;
});

2 events are handled by this javascript: the click on the anchor in the main view that shows the jQuery dialog and the form submission that will upload the file using an AJAX request and the HTML 5 File API.


text:
Q: Grafana Column no value suggestion in query builder I am using Grafana for visualisation for my Mariadb and Postgres databases. On Mariadb, there are suggestions in the query builder for the column row but not on Postgres. If I type the name myself, it shows the data correctly but no suggestion is shown. Can anyone help?

A: You don't have any suitable column (numeric type, e.g. int, float, ...) in zf1_table table, so that's a reason why editor is not offering any column in the select section.
Or very likely you don't have proper permissions: https://grafana.com/docs/grafana/latest/datasources/postgres/#database-user-permissions-important
So used Grafana DB user can't read table structure.


text:
Q: how to propagate uncaught errors in promise contexts to window.onerror? unlike what one may expect, the following code will not trigger the window.error handler
window.addEventListener("error",function(error){
    alert("uncaught error somewhere!");
});

(async function(){
let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
})();

(reason being "because the error occurs in a promise context" according to a comment on
this question: why doesn't fetch().json() errors trigger window.onerror? )
what is the correct way to explicitly propagate it to the window error handler?
this doesn't work either, for some reason it still doesn't propagate to window.error:
(async function(){
let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
})().catch(function(err){
    throw err;
});

this doesn't seem to work either (why? no idea)
(async function(){
let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
})().catch(function(err){
    let ev = new ErrorEvent(err.message, err);
    window.dispatchEvent(ev);
});

and this approach fails with the error Uncaught (in promise) DOMException: Failed to execute 'dispatchEvent' on 'EventTarget': The event provided is uninitialized., whatever that means
(async function(){
let foo= ((await ( await fetch("/no_json_plz_i_want_an_error")).json()));
})().catch(function(err){
  let ev= document.createEvent("ErrorEvent");
  ev.error=err;
  window.dispatchEvent(ev);
});

so.. what is the correct way to do it?

A: You can use unhandledrejection event to catch the promises error in window object instead.
Edit:
As fetch() will still return response object and there is no error throwing. You can throw a error when the response.ok is false. See function run1 below:
The run2 function will throw a JSON token error as the response.ok is false and it tries to parse the data.
You may try to run in your local environment because fiddle may wrap the error handling in the console.

window.addEventListener("unhandledrejection", function (e) {
  console.log("Error occurred: " + e.reason.message);
});

(async function run1() {
  try {
    let response = await fetch("/no_json_plz_i_want_an_error");
    if (response.ok) {
      const data = response.json();
    } else {
      throw new Error("Unable to fetch()");
    }
  } catch (err) {
    throw new Error(err);
  }
})();

(async function run2() {
  try {
    await (await fetch("/no_json_plz_i_want_an_error")).json();
  } catch (err) {
    throw new Error(err);
  }
})();


text:
Q: load html string in ios swift except UIWebView I want to load the following html string in Uitableview cell.How to load it ?

\r\n\t  Whether you are viewing a premium-quality 2D picture or seeing incredible 3D depth, images are breathtakingly real in Samsung Full HD. Combine with a 3D TV and 3D active shutter glasses to view the latest Hollywood 3D titles or amplify your viewing experience by upconverting 2D content to immersive 3D.\r\n

A: Then you have to take web view in your table view cell because without webview how you can load the html string. According to my knowledge it is not possible to load html query except UIWebView.
So, you can take UIWebView in tableview's cell and can load html to that webview in cellforrowatindexpath method.

A: you can use NSAttributed String for load in UILabel or use UItextView to load HTML String for e.g
let htmlString: String = "
\r\n\t  Whether you are viewing a premium-quality 2D picture or seeing incredible 3D depth, images are breathtakingly real in Samsung Full HD. Combine with a 3D TV and 3D active shutter glasses to view the latest Hollywood 3D titles or amplify your viewing experience by upconverting 2D content to immersive 3D.\r\n
"

let  attrStr: NSAttributedString = try! NSAttributedString(data: htmlString.dataUsingEncoding(NSUnicodeStringEncoding), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

yourlabel.attributedText = attrStr

for additional help see this
else if you need third party lib use RTLabel it will load the all type of string in label


text:
Q: having issue deploying angular app on netlify i'm having issues deploying my angular app to netlify, the app is working perfectly on my local host but when i deploy i get the following err
can anyone help out
9:41:28 PM: npm WARN config     [`cacache`](http://npm.im/cacache).
9:41:29 PM: npm ERR! code ERESOLVE
9:41:29 PM: npm ERR! ERESOLVE could not resolve
9:41:29 PM: npm ERR!
9:41:29 PM: npm ERR! While resolving: @angular/compiler-cli@14.2.6
9:41:29 PM: npm ERR! Found: @angular/compiler@14.0.3
9:41:29 PM: npm ERR! node_modules/@angular/compiler
9:41:29 PM: npm ERR!   @angular/compiler@"^14.0.2" from the root project
9:41:29 PM: npm ERR!   peer @angular/compiler@"14.0.3" from @angular/platform-browser-dynamic@14.0.3
9:41:29 PM: npm ERR!   node_modules/@angular/platform-browser-dynamic
9:41:29 PM: npm ERR!     @angular/platform-browser-dynamic@"^14.0.2" from the root project
9:41:29 PM: npm ERR!
9:41:29 PM: npm ERR! Could not resolve dependency:
9:41:29 PM: npm ERR! peer @angular/compiler@"14.2.6" from @angular/compiler-cli@14.2.6
9:41:29 PM: npm ERR! node_modules/@angular/compiler-cli
9:41:29 PM: npm ERR!   @angular/compiler-cli@"^14.0.2" from the root project
9:41:29 PM: npm ERR!   peer @angular/compiler-cli@"^14.0.0" from @angular-devkit/build-angular@14.0.3
9:41:29 PM: npm ERR!   node_modules/@angular-devkit/build-angular
9:41:29 PM: npm ERR!     dev @angular-devkit/build-angular@"~14.0.3" from the root project
9:41:29 PM: npm ERR!   2 more (@angular/localize, @ngtools/webpack)
9:41:29 PM: npm ERR!
9:41:29 PM: npm ERR! Conflicting peer dependency: @angular/compiler@14.2.6
9:41:29 PM: npm ERR! node_modules/@angular/compiler
9:41:29 PM: npm ERR!   peer @angular/compiler@"14.2.6" from @angular/compiler-cli@14.2.6
9:41:29 PM: npm ERR!   node_modules/@angular/compiler-cli
9:41:29 PM: npm ERR!     @angular/compiler-cli@"^14.0.2" from the root project
9:41:29 PM: npm ERR!     peer @angular/compiler-cli@"^14.0.0" from @angular-devkit/build-angular@14.0.3
9:41:29 PM: npm ERR!     node_modules/@angular-devkit/build-angular
9:41:29 PM: npm ERR!       dev @angular-devkit/build-angular@"~14.0.3" from the root project
9:41:29 PM: npm ERR!
9:41:29 PM: Build was terminated: Build script returned non-zero exit code: 1
9:41:29 PM: Creating deploy upload records
9:41:29 PM: Failing build: Failed to build site
Top comments (0)

enter image description here

A: The npm install command fails. clean your package.json or try npm install --force
to clean your package.json set the same angular version to all your angular libraries.

A: One possible solution is to use a .npmrc file to specify options during the install.
If you haven't already, add a .npmrc file to the project root with the following content:
legacy-peer-deps=true

For more information on what this option does, see: What does npm install --legacy-peer-deps do exactly? When is it recommended / What's a potential use case?


text:
Q: ArrayList returning empty in tests and UI? Here's my code. I apologize for the sloppiness but essentially what it's supposed to do is simulate the backwards learning algorithm used by switches. The handleInput method takes in the src and dest MAC addresses and a port number and adds the src MAC and port# as a HashMaps into an ArrayList. The whole method is useless right now because none of the HashMaps stay in the ArrayList for some reason. Any help is much appreciated!
public class Switching {
    ArrayList<HashMap> switchTable = new ArrayList<HashMap>();

    public String handleInput(String srcMacAddress, int portNumber, String destMacAddress){
        String output = "";
        HashMap tableEntry = new HashMap();
        tableEntry.put(srcMacAddress, portNumber);
        for (HashMap hm : switchTable) {
            if (hm.containsKey(destMacAddress)) {
                 output += hm.get(destMacAddress).toString();
            } else {
                 output += "Ports flooded";
            }
        }
        switchTable.add(tableEntry);
        return output;
    }

    public ArrayList<HashMap> getTable(){
        return switchTable;
    }

public class SwitchingTests {
    @Test
    public void testSwitching(){
        new Switching().handleInput("123456", 12, "abcdef");
        ArrayList<HashMap> switchingTable = new Switching().getTable();
        Assert.assertEquals(switchingTable.toString(), "[{123456=12}]");
    }
}

A: You are creating a Switching object and call handleInput(...) on it and then proceed to create a new Switching object and get its table.
You need to get the table from the one you already created.
public class SwitchingTests {
    @Test
    public void testSwitching(){
        Switching switching = new Switching();
        switching.handleInput("123456", 12, "abcdef");
        ArrayList<HashMap> switchingTable = switching.getTable();
        Assert.assertEquals(switchingTable.toString(), "[{123456=12}]");
    }
}

A: inside your handleInput method you are creating new switchTable.
 what you have to do is to change your line
switchTable = new ArrayList() to switchTable = getTable();


text:
Q: Any ASP.NET Opensource project that works on both SQL Server and MS Access DB? I searched on Google and I can't find any, do you know some ?

A: Not that I'm aware. Most open source projects however use one specific database engine (which makes sense), or xml (for example dasBlog).
However you can always swap your SQL Server for MS Access in a project if you want. The provider system for membership etc in ASP.NET itself is already a great example of that possibility (though not open source as it comes from Microsoft). For example take a look at this tutorial: Using Access instead of SQL server for your ASP.NET Application Services.
Personally I would rather find it strange to see an open source project making use of 2 different, especially MS Access in the first place. People tend to use SQL Server Express or SQLite or SQL CE for something like this.


text:
Q: What happens after shutting down the PC via subprocess? I try to turn my pc off and restart it on LAN.
When getting one of the commands (turnoff or restart), I execute one of the followings:
subprocess.call(["shutdown", "-f", "-s", "-y"])  # Turn off
subprocess.call(["shutdown", "-f", "-r", "-t", "-c", "-y"]) # Restart
I'd like to inform the other side if the process was successfully initiated, and if the PC is in the desired state.
I know that it is possible to implement a function which will check if the PC is alive (which is a pretty good idea) several seconds after executing the commands, but how one can know how many seconds are needed? And what if the PC will be shut down a moment after sending a message stating that it is still alive?
I'm curious to know- what really happens after those commands are executed? Will the script keep running until the task manager will kill it? Will it stop running right after the command?

A: Programs like shutdown merely send a message to init (or whatever modern replacement) and exit immediately; it's up to it what happens next.  Typical Unix behavior is to first shut down things like SSH servers (which probably doesn't kill your connection to the machine), then send SIGTERM to all processes, wait a few seconds (5 is typical) for signal handlers to run, and then send SIGKILL to any survivors.  Finally, filesystems are unmounted and the hardware halt or reboot happens.
While there's no guarantee that the first phase takes long enough for you to report successful shutdown execution, it generally will; if it's a concern, you can catch the SIGTERM to buy yourself those few extra seconds to get the message out.


text:
Q: Check the irreducibility of the polynomial over $\mathbb Z$
*

*$f_1(x) = x^5 + 5x^2 + 1$

*$f_2(x) = x^4 - x^3 + 14 x^2 + 5x + 16$
Use the result if $p(x)$ is a monic polynomial with integer coefficient and $p(d) \neq 0$ for all integer $d$ dividing the constant term of $p(x)$ , then $p(x)$ has no root in $\mathbb Q$
Thus both $f_1(x)$ and $f_2(x)$ have no root in $\mathbb Z$. Also we can not apply Eisentein  Criterion. Give me any idea how to show that $f_i's$ are irreducible

A: Both polynomials are irreducible.
Hint for $f_1$: Use reduction modulo $2$ and that $x^2+x+1$ is the only irreducible polynomial in $\mathbb{F}_2[x]$ of degree $2$.
Hint for $f_2$: Use reduction modulo $5$. (Perhaps there is something more elegant.)


text:
Q: If $E\subset F$ then $\inf E\ge\inf F$ and $\sup E\le\sup F$ Suppose
$\emptyset\neq E\subset F \subset \mathbb R$
Prove that $\inf E \ge \inf F$ and $\sup E \le \sup F$.
The second part I kind of understand. If $E$ is a subset of $F$ and $\sup F$ is an upper bound for $F$ then $\sup F$ is going to be an upper bound for $E$.
Therefore $\sup E \le \sup F$
But the infinitum part I am not sure how to show.

A: The infimum of $F$ is the greatest element of $\mathbb{R}$ that is less or equal to all elements of $F$ so, since $E \subset F$ is also less or equal to all elements of $E$. If there are no elements in $F$ less than all elements of $E$ than it is also the infimum of $E$, else it is less than  inf$(E)$.


text:
Q: Return string rather than database entry in CSV export using csv_from_result I am using codeigniter to produce a CSV from a database entry. The following code works
$this->load->dbutil();
$csv = $this->dbutil->csv_from_result($stories);
echo $csv;

$name = 'data.csv';

// Build the headers to push out the file properly.
header('Pragma: public');     // required
header('Expires: 0');         // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Disposition: attachment; filename="'.basename($name).'"');  // Add the file name
header('Content-Transfer-Encoding: binary');
header('Connection: close');
exit();

force_download($name, $csv);
fclose($fp);

However, I have two questions.
1) Why does my code rely on echoing $CSV? It returns a blank cvs if I comment out this line.
2) How do I take the $CSV variable and edit it. At the moment my database stores some information as integers that the controllers turn to strings in the normal running of the site i.e. I might store the priority in the database as 0,1,2 but in the view I show Urgent,high,low. I would like to show these strings in the exported CSV rather than the database entry. I am a bit confused as to how I do this. I was thinking of a loop with a switch statement but I dont really know how to interact with the $CSV variable - Or should I be doing this in the model where the data is still in an object rather than csv_from_result()

A: 1) $csv contains all the information, it is all the content that makes up your file. That's why if you don't echo it out you just get a blank CSV file.
2) You don't want to edit $csv, that variable contains everything ready to go. You want to edit $stories, which from the looks of what you have pasted above contains everything from your database that then gets converted into CSV by $this->dbutil->csv_from_result. Look through your code and find where $stories is loaded, then modify that.


text:
Q: Filter function for nested lists in dr racket I am looking for a function that does what "filter" is used for, but without using filter. On top, it should also filter nested lists.
E. g. list ( 1 2 (list 3 'a 'b) 3 4) should return list (1 2 (list 3) 3 4).
I already have the function to filter. My thought is, that I have to distinguish in the beginning of the function, if first lst is a list itself.
What I got so far is:
     (define (my-filter pred lst)
     (cond ((null? lst) null)  ;;(after this I would try to test if it is a list itself, but I am not sure how)
    ((pred (first lst))
     (cons (first lst) (my-filter pred (rest lst))))
     (else (my-filter pred (rest lst)))))

A: As it has been said in the comments, a possible solution is:
(define (my-filter pred lst)
  (cond [(null? lst) null]
        [(list? (first lst)) (cons (my-filter pred (first lst))
                                   (my-filter pred (rest lst)))]
        [else (if (pred (first lst))
                  (cons (first lst) (my-filter pred (rest lst)))
                  (my-filter pred (rest lst)))]))

Example
> (my-filter number? '(1 a 2 (3 (b 4) c) 5 6 d 7))
'(1 2 (3 (4)) 5 6 7)

> (my-filter (lambda (x) (not (number? x))) '(1 a 2 (3 (b 4) c) 5 6 d 7))
'(a ((b) c) d)


text:
Q: Meta-analysis with mean and sample size but without standard deviation? I'm doing meta-analysis for a treatment done in seeds. I have approximately 130 series with value of the control mean (Xc), its treated homologous mean (Xe) for crop yield and the number of replications (Nc and Ne) of each experiment which I'll use the number of replications as "sample size". From those 130 studies, I got like 5% of them with diverse measures of variance: pooled standard deviation for control and treated, standard deviations, P values… (see the picture) that's why I think it's not good idea to impute.
I believe that I can still do meta-analysis without standard deviation by calculating effect size (ES) with log response ratio (lnR) of means and later weight the studies using sample sizes as measure of variance.
I have also seen some studies that just defined the variance as I think the inverse of sample size, but I'm not sure how valid or accepted that is as a method.
Would lnR be the best solution? Anybody has done meta-analysis in this fashion or knows the best way to proceed?
I would be happy to hear any R codes that could help for the analysis.

Thanks in advance.


text:
Q: What happens if we schedule many jobs in apscheduler I have a flask server running which also has jobs scheduled and run using apscheduler. Provided that each of my jobs have their own state, how many jobs can we schedule using apscheduler. Does it invoke the job on a separate thread if two jobs tend to run at the same time?
scheduler.add_job(report1,cron......)
scheduler.add_job(merge_prs, con.....)
scheduler.add_job(decline_stale_prs, interval.....)
scheduler.add_job(report2, cron.....)

In short if I schedule many jobs in a single instance of apscheduler, what are the repercussions? In my understanding there would be issues with memory and state. I'd like to hear other perspectives.


text:
Q: Search form does not work in my website I have a search form in my website which is located in my header.php and I want it to be shown in all of my pages for this reason I have a searchform.php file where I have inserted this code:

<form method="get" action="<?php bloginfo('url'); ?>/">
<input type="text" name="" placeholder="Search here..."onfocus="this.placeholder = ''" onBlur="this.placeholder='Search here...'"/>
</form>
<img src="<?php bloginfo('template_url');?>/images/search-icon.png" alt="search-icon">

And in my header.php I have added this piece of code:
<?php get_search_form(); ?>

On the other hand I've put this code inside my search.php file:

You searched for " <?php echo esc_html( get_search_query( false ) ); ?> ". Here are the results:

Now when I search for something I get no results. What is the problem? please help me.

A: You're missing the name of the search text input, so replace:
name=""

with
name="s"

Then take a look at searchform.php in the default themes, like Twenty Sixteen:
<form role="search" method="get" class="search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">

                <?php echo _x( 'Search for:', 'label', 'twentysixteen' ); ?>
                <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder', 'twentysixteen' ); ?>" value="<?php echo get_search_query(); ?>" name="s" />

        <button type="submit" class="search-submit"><?php echo _x( 'Search', 'submit button', 'twentysixteen' ); ?></button>
</form>

as an example for e.g. attribute escaping.


text:
Q: Pass the parameter in Vaadin 14 between two routes Help me, please, to make navigating between views in vaadin application.
In OrdersView class I create a link like
UI.getCurrent().navigate(FullOrderView.class, new RouteParameters("orderId", "123"));

In FullOrderView class I specify a route like this
@Route("order/:orderId")
public class FullOrderView extends AppLayout implements HasUrlParameter<String>{
    @Override
    public void setParameter(BeforeEvent event, String parameter) {
    }

but I get an error
java.lang.IllegalArgumentException: Navigation target 'com.example.crudwithvaadin.FullOrderView' requires a parameter.

If I remove a "implements HasUrlParameter" and setParameter() I get an error
No route found for the given navigation target 'com.example.crudwithvaadin.FullOrderView' and parameters '{}'

How do I fix the error and pass the parameter correctly?
Thanks!

A: You are combining different Router features. The usage of Route template parameter (:orderId) has to be used in conjunction with BeforeEnterObserver instead of HasUrlParamter.


text:
Q: Safe to remove empty keys from URLs? My understanding in URLs are somewhat limited but I do understand the basic concept of domain name, sub-domain and parameters like key=value. However, at the moment I'm working with some ugly URLs provided from affiliate-companies. I manage those by setting up 301 redirects.
If I receive one of those ugly links they sometimes end with a key but no value like www.example.com/affiliate?id=123&trackid= ending with a key "trackid" but no value makes no sense to me.
Is it safe to remove that parameter in my example everything after the "3"? Making the URL www.example.com/affiliate?id=123.

A: The URL is supplied to the server as-is, so the server can see the entire string and realize wether an parameter is set without a value or if it is left out.
However, server code usually does not differentiate between the two and handle empty parameters like undefined parameters. So it is possible for the server to technically see the difference, but they usually just handle both the same way.


text:
Q: S3 Glacier 35 random restore per PB limit In the doc goes:

However, if you need to restore a large amount of data, keep in mind
that the S3 Glacier and S3 Glacier Deep Archive storage classes are
designed for 35 random restore requests per pebibyte (PiB) stored per
day.

Upon scouting the API docs and other docs I could not find a second reference to this limit. Also my experiments show that I can archive and restore 300+ small objects to Deep Archive without hitting this limit.
Also in a whitepaper goes:

If you need to run this solution on  a  large  number  of  objects  in
Glacier  or  Deep  Archive,  keep  in  mind  that  these  storage
classes are designed for 35 random restore requests per pebibyte (PiB)
stored per day. You can  increase  restore  throughput  by  sequencing
restores  by  object  creation  date  to  reduce randomness. You can
also spread checksum calculations over a number of days or weeks to
remain  below  therandom  restore  entitlement  and  maintain  restore
throughput  for  other access needs.

This only adds more confusion as how "randomness" is defined.
Moreover, I found that the InitiateJob API is not armed with 429 Resource Limit Exceeded.
So, what exactly are "random restore requests"? What is the implication of this limit?


text:
Q: select a neighborhood of points and convert it to a vector I have a data that is actually an image in form of 256 x 256 matrix. I want to select a neighborhood of points and convert it to a vector. Then apply some clustering algorithms. I am new to R and need some help with the code. I have created a toy dataset to show what I want to do.
d<- matrix(rbinom(8*8,1,0.5),8,8)
d
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    0    0    1    0    0    0    0    1
[2,]    1    1    1    0    1    1    1    1
[3,]    1    1    1    1    0    1    1    1
[4,]    0    0    1    1    1    1    1    0
[5,]    0    0    1    0    0    1    1    1
[6,]    1    0    0    0    0    0    1    0
[7,]    0    0    1    1    0    1    1    0
[8,]    1    1    0    1    1    0    1    0

Starting at point d[2,2], I want to select a neighborhood of 8 points around it and convert it into a vector. So for d[2,2] those points will be top 3 d[1,1],d[1,2],d[1,3], adjacent left d[2,1] adjacent right d[2,3] and bottom 3 d[3,1],d[3,2] and d[3,3]. That will be as follows:
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    1    1    1
[3,]    1    1    1

Now convert it to a vector in R^9 as v1=(0,0,1,1,1,1,1,1,1). Then, I want to do this for all points that are not on boundry of matrix (i.e. first and last rows and first and last columns). I have not idea how to proceed and will appreciate any help. Thanks in advance.

A: You can proceed with a nested for loop:
ddim <- dim(d) - 1
vect <- list()
for(i in seq(ddim[1])[-1]) {
    for(j in seq(ddim[2])[-1]) {
        vect <- c(vect, list(c(d[(i-1):(i+1), (j-1):(j+1)])))
    }
}

There may be optimised solution (nested for loop is bad) but this works if you're not too burdened with data.


text:
Q: can't call/send sms between 2 android emulators Even after starting up 2 emulators when I dial to call the other emulator it disconnects automatically after pressing the dial button its all the same case for sending an sms can't send message from one emulator to another

A: You cannot call or SMS from one emulator to another directly. Instead, you can simulate the aforementioned, as shown step by step in the following links:
http://www.dotnetexpertsforum.com/simulating-sms-in-android-emulator-t1396.html
http://www.slegg.net/simulate-incoming-call-with-android-emulator/

A: When you want to call between emulators you just need to use the console port number of the emulator you want to call to into the dialer of the emulator you want to call from. This is displayed as a number in the title of the emulator window, e.g. 5554:my_emulator_name. In this case you would call to 5554.


text:
Q: Oracle Forms/Applications in Internet Explorer 8 using JInitator Has anyone been able to get Oracle Forms running JInitator to loan in Internet Explorer 8 yet?  I have tried removing all add-ons, various version of Java, add the domain to the trusted sites using wildcards, and using compatibility mode to no avail.  I am looking to get our Oracle guys to kick there Internet Explorer 6 habit.  This is related to Oracle E-Business.

A: Replacing the jvm.dll did not work for me. The proper way to switch to Sun's Java VM which worked for me is by changing this
baseHTMLjinitiator=basejini.htm

to
this
baseHTMLjinitiator=basejpi.htm

in the formsweb.cfg file. IE8 on XP SP3, DEP enabled.

A: Yes as of now IE8 is not certified for Oracle Apps. You may hear a good news soon!

A: To solve this problem you need to replace the file C:\Program Files\Oracle\JInitiator x.x.x.xx\bin\hotspot\jvm.dll with the sun version of the file.
On my system the sun version is here C:\Program Files\Java\jre6\bin\client\jvm.dll

A: I have successfully installed Oracle Forms 10g on Windows7 and get both JPI and Jinitiator working.
Steps

*

*Install Dev10g

*Apply Patch p5983622_10123_WINNT

*Manually install JRE 1.6 upd 20

*Configure formsweb.cfg for JPI

*This is preferred method as you don't have to do following steps on each client

If you want to run using Jinitiator

*

*Configure formsweb.cfg for Jinitiator

*Once Jinitiator is installed on client machine replace jvm.dll

A: As Mundit has said, it is still not certified.
Do you have access to Metalink? Note: 760326.1 When Will IE 8 Be Certified With E-Bussines Suite? gives some further information.

A: A colleague of mine told me to do the following:
Add server to Trusted Sites and then:

*

*Tools / Internet options

*Security tab -> Trusted Sites

*Click on Custom level... button

*scroll to the end and find "Enable XSS filter" option (3rd from the bottom)

*set it to Disable

This works for me with 11i and R12 apps.
Good luck!

A: One thing to add to Simon's solution. I did the trick on one computer but couldn't repeat it on a second one. Finally, I discovered that replacing the file does not work when using the file jvm.dll from java 6 update 14. It worked fine when I used the jvm.dll file from version 13.

A: Here's something even more intersting about JINIT.  It was de-supported by Oracle as of July 31st.  You might want to consider moving to the SUN JPI instad.  This is the recommended route by Oracle now, and since JINIT will not be getting updates it's the safest.

A: You guys are great!  I was pulling my hair off their roots and now got it fixed.

*

*I went to Control Panel/System/Advanced tab/Startup and Recovery panel hit Settings.  Then in the System Startup panel hit Edit. There made noexecute=AlwaysOff and saved.

*As per Simon I swapped the Oracle jvm.dll with the Java version.  I had to downgrade that to jvm.dll version 10.0.0.23 though.

*Also as per Simon I went to Tools/Internet Options/Security/Trusted Sites/Custom Level and disabled Enable XSS Filter.

Not sure whether #1 applies to everyone but it was necessary for me.  Good Luck!
Fouwaaz

A: We're having a similiar problem.
I believe Oracle is aware of this, and is working on a patch, which is not ready yet.

A: *

*Install the latest JRE from Sun. I have installed "jre-6u10-windows-i586-p-s.exe".

*Copy the jvm.dll (appx Ver 11.0.0.15 size 2.25 MB (2,359,296 bytes)) from the "C:\Program Files\Java\jre6\bin\client" folder and paste it to folder where the Jinitiator is installed (default location) e.g "C:\Program Files\Oracle\JInitiator 1.3.1.22\bin\hotspot".

*It will work fine with the IE8 browser.
Thanks for the help.


text:
Q: System generated approval of document Our documents need signature and fiscal approval. We would like the approval to be sent by our procurement system. What's the API call to approve the contract?

A: It sounds like you're asking if you can make an API call from your procurement system to "sign".  DocuSign does not have way to apply signatures without a human being taking the action.  You'd need to get the procurement "signature" on the PDF before sending it to DocuSign.  Or you could use a regular text field and do a data merge to fill it in with "electronically approved by Procurement" if that would work.  It would remain your system's responsibility to prove the audit trail of that pseudo signature.