text:
Q: Liferay 6.2 custom fulltext search portlet implementation I want to implement custom search portlet so I can search through attributes that are part of custom structures.
Let's say that I've made structure called "Literature" which contains attributes as author, content, title, annotations, section etc.
I want to create "advanced" search where can I select particular structure type (Literature, Verdict or Legislative), particular sections that are represented with another attribute of these structure types (for example select only literatures with section PPV or literatures with section APS) etc.
I tried to use faceted search but I didn't find out how to include these structure's attributes into query:
This is my "search" code:
 SearchContext searchContext = SearchContextFactory.getInstance(httpServletRequest);
 Map<String, Serializable> attributes =    new HashMap<String, Serializable>();
 attributes.put(Field.TITLE, "some word");
 attributes.put("paginationType", "regular");
 searchContext.setAttributes(attributes);

 Facet assetEntriesFacet = new AssetEntriesFacet(searchContext);
 assetEntriesFacet.setStatic(true);
 searchContext.addFacet(assetEntriesFacet);

 Facet scopeFacet = new ScopeFacet(searchContext);
 scopeFacet.setStatic(true);
 searchContext.addFacet(scopeFacet);

 String[] entryClassNames = { JournalArticle.class.getName() };
 searchContext.setEntryClassNames(entryClassNames);

 hits = FacetedSearcher.getInstance().search(searchContext);
 List<Document> docs = hits.toList();

So how to include in facet search my structure specific attributes like "section" etc...
My other question is that there is a problem with punctuation. Let's say that title contains word "Právo". When I run search with word "pravo" it will bring 0 results but when I run search with "právo" it will find me somw results. Is there any workaround for search with punctuation?
Thanks,
Patrik

A: Searching FT index is quite messy in 6.2, I managed to do it this way (groovy):
Indexer indexer = IndexerRegistryUtil.getIndexer(JournalArticle.class.name);

SearchContext sc = new SearchContext([
        companyId: PortalUtil.defaultCompanyId,
        groupIds: groupId
]);

String testText = DDMIndexerUtil.encodeName(
        structureId, "custom-field-name", LocaleUtil.fromLanguageId("pl_PL"));

BooleanClause testTextClause = BooleanClauseFactoryUtil.create(
        sc, testText, "Search term", BooleanClauseOccur.MUST.getName())

sc.setBooleanClauses(testTextClause)

sc.setStart(QueryUtil.ALL_POS);
sc.setEnd(QueryUtil.ALL_POS);

sc.setAttribute("paginationType", "none");

hits = indexer.search(sc);

hits.toList().each { Document doc ->
    JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(groupId, doc.get("articleId"))
    println "${ja.getTitle(LocaleUtil.fromLanguageId("pl_PL"))}"
}

To run this you need to have structureId (check journalarticle table) and groupId.


text:
Q: cakephp find with count equivalent with this query SELECT COUNT(*) FROM `users` where usergroup_id = 4 AND studio_id = 380 AND userstatus_id = 1

On this query I am getting a result of 4 which is my expected output, but when doing this query:
$this->User->find('count',array('conditions'=>array(
                                        'User.studio_id'=>380,
                                        'User.usergroup_id'=>4,
                                        'User.userstatus_id'=>1)))

I am getting a result of 8
What do you think is the problem here? Feels like my 2nd code is wrong.
I am a newbie in cakePHP.
Your help would be greatly appreciated and rewarded!

A: The query and the CakePHP find('count', ... should produce the same thing.  The likely difference (per a few of the comments) is your $recursive level (see CakePHP recursive).
I'm a big fan of just setting:
public $recursive = -1;

in your AppModel - then you don't have to worry about it ever again, as leaving it at -1 is best practice IMO.  Then, if you ever want to retrieve additional associated model data, just use CakePHP's Containable.
If you don't want to set it to -1 across the entire site, just set it right before your query:
$this->User->recursive = -1;
$this->User->find('count',array('conditions'=>array(
    'User.studio_id'=>380,
    'User.usergroup_id'=>4,
    'User.userstatus_id'=>1
)));

Site Note: Setting $recursive to ANYTHING other than -1 should be a red flag.  It's kind of a cool concept, but in practice, it will cause you many headaches as your site grows.  Set it to -1 in the AppModel like suggested above, then forget it even exists.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jqGrid doesn't overflow correctly I'm having an annoying problem with jqGrid: Instead of scrolling the lines, it just keeps adding them one bellow the other and doesn't stop at a certain height. What am I doing wrong? :S

<link rel="stylesheet" type="text/css" media="screen" href="libraries/jquery/custom-theme/jquery-ui.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="libraries/jquery/jqGrid/css/ui.jqgrid.css?" />

A: Your HTML file has no  element, no DOCTYPE before  and has unclear encoding (should be utf-8 and defined with <meta>, see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:first_grid as an example). You should also remove '?' after "ui.jqgrid.css" and change <= to < in the loop.
On http://www.ok-soft-gmbh.com/jqGrid/Overflow.htm you can see the same file in a little modified form which works.


text:
Q: Orthogonal check; incorrect maths or function usage? I am comparing 2 angles (in degrees) and I want to know if they are orthogonal.
So I use the following scipy.spatial.distance function:
print( dist.cosine([181], [1]) )

However it prints out 0.0. Shouldn't this result give me either 1 or -1? Ie, its in the opposite direction? Am I using the function wrong?

A: dist.cosine actually computes the cosine distance, which (wikipedia) is a term that

is often used for the complement in positive space, that is:
D C ( A , B ) = 1 − S C ( A , B )
where D C is the cosine distance and S C is the
  cosine similarity.

This isn't what you want at all. I'm no Python expert, but doesn't
math.cos(math.radians(181 - 1))

do what you want?


text:
Q: Making a PGF shape I'm having terrible trouble trying to declare a new shape with PGF and would appreciate help. What I would like to achieve is:

where the lighter grey boxes are \nodepart anchors, and the base shape is a rectangle, with a line drawn from the upper left corner to the middle bottom to the upper right corner.
Here is what I've tried:
\catcode`@=11
\pgfdeclareshape{decision}{%
  \inheritsavedanchors[from=rectangle]%
  \inheritanchorborder[from=rectangle]%
  \inheritanchor[from=rectangle]{center}%
  \foreach \anchor in {north,north west,north east,center,west,east,mid,
    mid west,mid east,base,base west,base east,south,south west,south east}{%
    \inheritanchor[from=rectangle]{\anchor}}%
  \nodeparts{text,false,true}%
  \savedanchor{false}{%
    \pgf@x=.1\wd\pgfnodeparttextbox%
    \pgf@y=.1\ht\pgfnodeparttextbox%
  }%
  \savedanchor{true}{%
    \pgf@x=.9\wd\pgfnodeparttextbox%
    \pgf@y=.1\ht\pgfnodeparttextbox%
  }%
  \inheritbackgroundpath[from=rectangle]%
  %\beforebackgroundpath{%
  %  \pgfpathmoveto{\pgfpointadd{      %}%
}
\catcode`@=12
\tikz \node[decision] {};
\bye

Trying to compile the above (unfinished) definitions I get an error:
! Missing control sequence inserted.
<inserted text>
                \inaccessible
<to be read again>
                   f
\pgf@sh@savedpoints ...53297pt}{-3.53297pt}}\def f
                                                  alse{\pgfqpoint {0.0pt}{0....

UPDATE
After following @cjorssen's advice in a comment, I changed the first arguments of \savedanchor commands to be a command (i.e., \true, \false), and then I get a different error:
! Missing number, treated as zero.
<to be read again>
                   \pgfnodepartfalsebox
\pgfsys@hbox #1->\pgfsys@beginscope \setbox #1
                                              =\hbox {\box #1}\wd #1=0pt\ht ...

A: I improved your code a bit, I see that in the mean time Andrew has already explained everything I was going to in here. I will just add the code, so that you have a starting point.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes.multipart}
\begin{document}
\makeatletter
\newbox\pgfnodepartfalsebox
\newbox\pgfnodeparttruebox
\pgfdeclareshape{decision}{%
  \nodeparts{text,false,true}%
  \inheritanchorborder[from=rectangle]%
  \inheritanchor[from=rectangle]{center}%
  \foreach \anchor in {north,north west,north east,center,west,east,mid,
    mid west,mid east,base,base west,base east,south,south west,south east}{%
    \inheritanchor[from=rectangle]{\anchor}}%
  \savedanchor\northeast{
    \pgf@x=.5\wd\pgfnodeparttextbox%
    \advance\pgf@x by\wd\pgfnodeparttruebox%
    \advance\pgf@x by2ex%
    \pgf@y=\ht\pgfnodeparttextbox%
  }
  \savedanchor\centerpoint{%
    \pgf@x=0pt%
    \pgf@y=0pt%
  }
  \savedanchor\southwest{
    \pgf@x=-.5\wd\pgfnodeparttextbox%
    \advance\pgf@x by-\wd\pgfnodepartfalsebox%
    \advance\pgf@x by-2ex%
    \pgf@y=-\ht\pgfnodeparttextbox%
    \advance\pgf@y by-\ht\pgfnodepartfalsebox%
    \advance\pgf@y by-\ht\pgfnodepartfalsebox%
  }
  \savedanchor\falseanchor{%
    \pgf@x=-.5\wd\pgfnodeparttextbox%
    \advance\pgf@x by-\wd\pgfnodepartfalsebox%
    \advance\pgf@x by-2ex%
    \pgf@y=-\ht\pgfnodeparttextbox%
    \advance\pgf@y by-\ht\pgfnodepartfalsebox%
    \advance\pgf@y by-\ht\pgfnodepartfalsebox%
    \advance\pgf@y by.2\ht\pgfnodepartfalsebox%
%     \advance\pgf@x by\wd\pgfnodepartfalsebox%
  }
  \savedanchor\trueanchor{%
    \pgf@y=-\ht\pgfnodeparttextbox%
    \advance\pgf@y by-\ht\pgfnodepartfalsebox%
    \advance\pgf@y by-\ht\pgfnodepartfalsebox%
    \pgf@x=.5\wd\pgfnodeparttextbox%
    \advance\pgf@x by\wd\pgfnodeparttruebox%
    \advance\pgf@x by2ex%
    \advance\pgf@x by-\wd\pgfnodeparttruebox%
    \advance\pgf@y by.2\ht\pgfnodepartfalsebox%
  }
  \anchor{text}{%
    \centerpoint
    \pgf@x=-.5\wd\pgfnodeparttextbox%
    \pgf@y=-.5\ht\pgfnodeparttextbox%
  }
  \anchor{false}{%
    \falseanchor%
  }%
  \anchor{true}{%
    \trueanchor
  }%
  \backgroundpath{%
    \northeast
    \pgf@xa=\pgf@x \pgf@ya=\pgf@y
    \southwest
    \pgf@xb=\pgf@x \pgf@yb=\pgf@y
    \pgfpathmoveto{\pgfpoint{\pgf@xa}{\pgf@ya}}
    \pgfpathlineto{\pgfpoint{\pgf@xa}{\pgf@yb}}
    \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@yb}}
    \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@ya}}
    \pgfpathclose
    \pgfmathsetlength{\pgf@xc}{.5\pgf@xa+.5\pgf@xb}
    \pgfpathmoveto{\pgfpoint{\pgf@xa}{\pgf@ya}}
    \pgfpathlineto{\pgfpoint{\pgf@xc}{\pgf@yb}}
    \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@ya}}
    \pgfusepath{stroke}
  }%
}

\makeatother

\begin{tikzpicture}
  \node[decision, draw] {text \nodepart{false} false\nodepart{true}true};
\end{tikzpicture}

\end{document}

This looks somewhat like your example:

You should definitely improve, using keys and making the anchors depend on minimum sizes, inner and outer sep, etc. At least this gives you a starting point from where you can fill in the remaining blanks.

A: There's a few issues here:

*

*As cjorssen says in the comment, the first argument of \savedanchor has to be a command sequence.  I'd go for \<part>anchor.

*Saved anchors are not anchors.  They then have to be used to define anchors.  So you need \anchor{true}{\trueanchor} and likewise (and the true and false anchors have to be defined).

*If you're using new parts that haven't been used in other shapes, you need to declare new boxes for them.  So you need \newbox\pgfnodeparttruebox and likewise.

*You shouldn't inherit your anchors and border from the rectangle shape.  These will be defined solely in terms of the text part and not in terms of the whole thing.  If you define the north west and south east (I think I have those right) in terms of the new data, then you can inherit the rest of the anchors from the rectangle since all the other anchors (and the background path) are defined in terms of these two.

*So the main hassle is going to be figuring out how big the outer rectangle should be given the sizes of the smaller ones.  Once you have that, the rest should be plain sailing!  (Remember to make things customisable!  Use PGF keys whenever you find yourself wanting to specify an arbitrary dimension.)

*The code for the circle split multipart node was invaluable to me in figuring out some of the above.  I recommend taking a look at it.


text:
Q: How to compare a String-Array Android devs!
1) I have tried to compare a string-array declared in my string.xml (I don't know if it's possible):
<string-array name="menu_array">
        <item>Pizzas</item>
        <item>Baguetes</item>
        <item>Calzones</item>
        <item>Esfihas</item>
        <item>Refrigerantes</item>
        <item>Vinhos</item>
        <item>Cervejas</item>
</string-array>

2) I have a layout with an ImageView, to update images corresponding to each menu item string-array:
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:gravity="center"
    android:clickable="true"
    android:onClick="selecionarOpcao"
    android:padding="32dp" />

3)I am using a navigation drawer. This is a class with a Fragment to show an image of item called:
public static class MenuFragment extends Fragment {
    public static final String ARG_PRODUTOS_NUMBER = "produtos_number";

    public MenuFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState)
    {
        View rootView =
            inflater.inflate(R.layout.fragment_menu, container, false);

        int i = getArguments().getInt(ARG_PRODUTOS_NUMBER);
        String menu = getResources().getStringArray(R.array.menu_array)[i];

        int imageId = getResources().getIdentifier(
            menu.toLowerCase(Locale.getDefault()), "drawable",
            getActivity().getPackageName());

        ((ImageView) rootView.findViewById(R.id.image))
            .setImageResource(imageId);
        getActivity().setTitle(menu);
        return rootView;
     }
 }

4) I would like to call different Intents according to the item clicked, the image loaded... I have trying this form, but not succesfully.
public void selecionarOpcao(View view)
{
    switch (view.getId()) {
    case R.id.image:
        String[] produto =
            getResources().getStringArray(R.array.menu_array);
        if (produto.toString().equals("pizza")) {
            startActivity(new Intent(this, ListarActivity.class));
        } //Others Condictions
        break;
    }
}

As I compare these strings? Thanks guys!

A: String[] produto = getResources().getStringArray(R.array.menu_array);
if (produto.toString().equals("pizza")) {
    startActivity(new Intent(this, ListarActivity.class));
}//Others Condictions

replace with
String[] produto = getResources().getStringArray(R.array.menu_array);
for(String item in produto) {
    if (item.equals("pizza")) {
        startActivity(new Intent(this, ListarActivity.class));
    }//Others Condictions
}

UPDATE:
You can try set tag with string
((ImageView) rootView.findViewById(R.id.image)).setTag(menu); // in onCreateView

And use this tag in listener:
public void selecionarOpcao(View view)
{
    String menuString = (String) view.getTag();
    if(menuString.equals("Pizzas")){
    // start activity
    } else if /// Other Condition
}


text:
Q: PHP Variable Randomly Changes I have encountered a very weird and concerning problem in some of my PHP code. A variable that I have returns true in an IF statement when it clearly should return false.
$pr = $_SESSION['fin_print_printer']; //this should equal 0
print $pr; //this returns 0, as it should
if($pr == "L"){
   print "local";
} else {
       print "serve";
}
print $pr; //this returns 0 again, as it should

This prints "local" in my script (in between the two zeros) and does not print "serve". With over 100,000 lines of code in my project, I've not experienced this issue yet, and now I can't figure out what is going on.
If I do if($pr === "L"), then it works as expected, but the above does not.

A: PHP is trying to typecast 'L' into an int, which results in 0.
intval('L'); // 0

Change your code into the following so it will take types into account:
if($pr === "L")
{
    print "local";
}
else
{
    print "serve";
}

Or manually typecast $pr to a string.
// You can also to (string)$pr ("0" instead of 0)
if(strval($pr) == "L")
{
    print "local";
}
else
{
    print "serve";
}

A: Maybe if you use typecasting (I did't check it):
if ( (string)$pr == "L" ) {
   print "local";
} else {
       print "serve";
}

A: Little known approach: You can also do the casting like
if ("L" == $pr) {

Because with loose comparisons, PHP casts the right value to the left value's type, and as you've already been made aware, while string(1)"L" is casted to int(0), int(0) is casted to string(1)"0".


text:
Q: Two windows in separate thread becoming active together I have two modal dialogs and each dialog has one edit box. I am creating these dialog boxes in two separate threads. But sometimes when these dialog boxes become visible, both edit boxes are showing a blinking cursor and both windows are appearing active - which means that the title bars of both windows are appearing blue. I am not able to work out why this behaviour is being shown by the dialogs.
Can anyone help me in pointing out where I might be wrong??

A: Separate threads are separately schedulable, so unless the two threads coordinate their activity, it would be possible for both to be active at one time - as you describe - unless there is something in MFC that ensures that only one modal dialog can be active at a time.  Make sure the threads coordinate things so that only one of the dialogs is active at any given time.
Ah, the joys of multiple cores...


text:
Q: Partialised glue function does not work when called in different environment I've partialised the glue function in a project I'm working on so that we can use agreed-on delimiters without having to tell glue about them all the time. But when we go to use the partialised function inside another function, it stops working:
library(purrr)
library(glue)

glue_query <- partial(glue, .open = "<<", .close = ">>")

# case 1: use partialised function in same scope
x <- 15
glue_query("There are <<x>> apples here!")
#> There are 15 apples here!

# case 2: use partialised function in different scope
myfunc_partialised <- function(y) {
  glue_query("The thing I called y is actually <<y>>")
}
myfunc_partialised(15)
#> Error in eval(parse(text = text, keep.source = FALSE), envir): object 'y' not found

# case 3: use function directly
myfunc_regular <- function(z) {
  glue("The thing I called z is actually <<z>>", .open = "<<", .close = ">>")
}
myfunc_regular(15)
#> The thing I called z is actually 15

Created on 2021-07-09 by the reprex package (v2.0.0)
I get the sense that glue_query is looking for objects to interpolate in the environment it was defined in, rather than in the environment it's called in. Is that's what happening here? Can I direct it to use the calling environment? I'd like to use it throughout my package!
EDIT: I understand that glue has an .envir argument that controls which environment the expressions are evaluated in, but I'm not quite sure what to use to ensure it plays nice here!

A: It does seem that partial() makes it much more difficult to get the correct environment. Instead you can write your own wrapper
glue_query <- function(..., .open = "<<", .close = ">>", .envir=parent.frame()) {
  glue(..., .open=.open, .close=.close, .envir=.envir)
}

This will work with both the test cases you provided.

A: One alternative is to change the defaults of glue, define your function, the reset the defaults:
library(glue)
library(default)

default(glue) <- list(.open = "<<", .close = ">>")
glue2 <- glue
reset_default(glue)
#> function (..., .sep = "", .envir = parent.frame(), .open = "{",
#>     .close = "}", .na = "NA", .transformer = identity_transformer,
#>     .trim = TRUE)
#> {
#>     glue_data(.x = NULL, ..., .sep = .sep, .envir = .envir, .open = .open,
#>         .close = .close, .na = .na, .transformer = .transformer,
#>         .trim = .trim)
#> }
#> <bytecode: 0x0000000014c59d80>
#> <environment: namespace:glue>

# case 1: use partialised function in same scope
x <- 15
glue_query("There are <<x>> apples here!")
#> Error in glue_query("There are <<x>> apples here!"): could not find function "glue_query"
#> There are 15 apples here!

# case 2: use partialised function in different scope
myfunc_partialised <- function(y) {
  glue2("The thing I called y is actually <<y>>")
}
myfunc_partialised(15)
#> The thing I called y is actually 15

# case 3: use function directly
myfunc_regular <- function(z) {
  glue("The thing I called z is actually <<z>>", .open = "<<", .close = ">>")
}
myfunc_regular(15)
#> The thing I called z is actually 15

Created on 2021-07-09 by the reprex package (v0.3.0)


text:
Q: How to throw error in dropzone for maxfilesize? In my code I set the filesize 1mb , its work fine  but doesnot throw any error message how can I set?
 $(document).ready(function () {

        $("#my-dropzone").dropzone({
            maxFiles: 1,
            maxFilesize: 1,
            parallelUploads: 1,
            url: "upload.php",

            success: function (file,response) {

                file.previewElement.classList.add("dz-success");

            },

            error: function (file,response) {
                sv.previewElement.classList.add("dz-error");
            }
        });
    });

A: As the dropzone documentation says:

Since listening to events can only be done on instances of Dropzone,
  the best place to setup your event listeners, is in the init function

So set up the init callback and declare the success and error callbacks in the dropzone instance inside it:
$("#my-dropzone").dropzone({
    maxFiles: 1,
    maxFilesize: 1,
    parallelUploads: 1,
    url: "upload.php",
    init: function() {  // first you need an init callback
        success: function(file, response) {
            alert("Yeehaw!");
        },
        error: function(file, response) {  // and then can you have your error callback
            alert("Bah humbug...");
        }
    }
});

A: Consider this equivalent example:
try {
    var foo = function() {
        throw new Error("foo error");
    }
}
catch (error) {
}

foo();

You wouldn't expect the error caused by calling foo to be caught just because at the time foo was defined execution was inside the try block.
One solution is of course to use try/catch inside the body of the function that might throw, as you have shown. Another solution is to create a reusable "catching wrapper" function, perhaps like this:
function catchIfException(func, handler) {
    return function() {
        try {
            var args = Array.prototype.slice.call(arguments);
            func.apply(this, args);
        }
        catch (error) {
            handler(error);
        }
    };
}

    $(document).on('change', 'select',
        catchIfException(
            function(event) {
                event.preventDefault();
                event.stopPropagation();

                throw new Error('callPage method failed');
            },
            function(error) {
                console.log("error: " + error);
            }
        );
    );


text:
Q: CKEditor 5 : How to access raw text in Angular application I am using CKEditor 5 in my Angular application. I have to check that the text entered by the user in the editor has at least 100 characters. The problem is that the model bound to the editor receives the text + the html markup created by the editor for formatting. So I want somehow to bind a second property of my model to the raw text of the editor. Is this possible ?
In my component, I can access the editor like this :
 @ViewChild('ckeditor', { static: true }) private _ckEditor: CKEditorComponent;

I have tried this as a test but I can't find the raw text:
  onBlur() {
   console.log( this._ckEditor.editorInstance.document.getBody().getText());
  }

and the html :
<ckeditor #ckeditor id="desc" name="desc" [editor]="editor" (blur)="onBlur()"
                [(ngModel)]="mymodel"></ckeditor>

A: CK Editor 5 now provides Word Count Plugin which can be used to count words and characters entered in editor.

Documentation link : https://ckeditor.com/docs/ckeditor5/latest/features/word-count.html

A: You can add selector to ckeditor element (e.g. #myckeditor)
In ts file:
@ViewChild('myckeditor') myckeditor: CKEditor5.Editor;

And then get only plain text:
this.myckeditor.elementRef.nativeElement.innerText;


text:
Q: Merge two different Verdaccio storage folders (CouchDb databases) I am trying to set up a completely offline Verdaccio installation that I can use as a proxy for NPM packages for a small team of developers and for our build machine.
My challenge is that I would like to be able to update the offline npm packages from time to time (to add more packages). To do this, the only possibility I have is to use another machine (a laptop) that is outside this isolated network and has a separate Verdaccio installation and npm install the packages there. After installation I have the new tgz files in the storage folder. But my question is how do I merge the Storage folder from the offline Verdaccio installation with the Storage folder of the online one. Because I cannot do this manually, especially when you have packages with a lot of dependencies.
Is there some replication that I could easily setup (I am not an expert in CouchDb) or even a plain CLI instruction I could use? Or is there a way to achieve this with Verdaccio or some other utility?
Please bear in mind that this network is completely isolated (without network access) even if it is also used for development.

A: I just got the craziest idea that could be a good solution:
Whenever I will need to merge a new storage folder content, I will just copy it to a temporary location, start a new Verdaccio instance (with the storage at that location), then simply set the uplink of the main instance to the new/temporary one.
This way I will be able to run 'npm install' on the new packages on the main registry and this will automatically update the main storage folder (merge the databases). At the end I simply stop the second Verdaccio instance and cleanup the temp folder.

A: For this problem exactly I created this CLI tool: bulk-npm-publish.
How to use it:

*

*Copy the storage folder to your isolated network.

*Run bulk-npm-publish
3: Follow the steps (if you pass -i It will run interactively.

*Run the outputted publish script.

with this tool you can skip already existing packages.


text:
Q: How can I use a macro inside another macro in order to concat the definition of the macro to something? C/C++ I am trying to make a macro that will be take a predefined prefix and concatenate it to the wanted function name in the argument of the macro, but I have been unsuccessful.
For example, while this is the wanted function signature:
void somePrefix__someFunc(int a)

However, when I run it and check the symbol table of the program I end up with the expansion of:
FUNC_PREFIXsomeFunc

What am I doing wrong and how can I do this correctly?
The code I was trying to run:
#include <iostream>
#define CONCAT(A, B) A##B
#define FUNC_PREFIX somePrefix__
#define FUNC_NAME(_func) CONCAT(FUNC_PREFIX, _func)

void FUNC_NAME(someFunc)(int a)
{
    std::cout << a << std::endl;
}

int main()
{
    FUNC_NAME(someFunc)(2);
    return 0;
}

P.S: I tried using the macro without a CONCAT wrapper (directly trying to concat FUNC_PREFIX##_func), but it still did not work.

A: The ## is always applied before the macro "replacement list" is (re)scanned, so in case CONCAT is expanded before the other items, we won't get the desired result. Whenever we end up with a ## in the replacement list during macro replacement, it is then applied before any further replacement.
So you need an additional helper macro to expand the FUNC_PREFIX, so that it is expanded before CONCAT is:
#include <stdio.h>
#define CONCAT(A, B) A##B
#define CONCAT_EXPAND(A, B) CONCAT(A,B)
#define FUNC_PREFIX somePrefix_
#define FUNC_NAME(func) CONCAT_EXPAND(FUNC_PREFIX, func)

void FUNC_NAME(someFunc)(int a)
{
    printf("%s: %d\n",__func__, a);
}

int main()
{
    FUNC_NAME(someFunc)(2);
    return 0;
}

Output:
somePrefix_someFunc: 2


text:
Q: How to make page printable on clicking ctrl+P in yii2? I'm working on a demo project and i need to know how to make the page printable on just ctrl+P click. When i'm printing it just giving me a document without css and styles.
Here is the result I'm getting and the pdf which I want to get.

and I want this->

A: you need to write css for print media normal css will not work here.
so do these steps

*

*create new css file named as print.css

*copy css class from your normal stylesheet but only those class that used in your above layout not all.

*hide those part that you dont want to show on print.
like
.navigation, header, footer{display :none!important;}

now include this css file in your view file with extra attribute i. e. screen="print"
so full path look like this.
<link href="path/to/print.css" screen="print" />
or you can do this just by putting all css class in your main file under media query.
like @media(print){
// all your css classes that involves in your layout and extra css to hide div that you dont want
}


text:
Q: Adding the same object to multiple to-many relationships Have a core data question that I am trying to solve for the past couple of hours (5hrs).
I have two entities: Student and Class.
Student attributes: name, grade
Class attributes: name
Relationships:

*

*Student <<------>>Class, both have
to-many relationship.

*I create student 1.

*Then create Class 1, Class 2.

*I then add Student 1 to Class 1

*I then add Student 1 to Class 2.

Now when I change the grade of student 1 via the Class 1 its also change the grade for Class 2.
So how do I solve this problem. Thanks a bunch.
UPDATE (1):
According to answers, I have modeled the following:

I want to add the same student to different classes:
So is the relationship between Student and Class right?

A: Create a new Class to hold the Grade for a Student and Grade.  Something like StudentClassGrade or whatever

A: I would model it as
Grade:

*

*attribute: gradeValue (0-100)

*relationship: student

A Class contains a collection of these

*

*relationship: grades

it is highly suggested all relationships in core data have a reverse relationship, thus:
Grade:

*

*(reverse) relationship: class

Student:

*

*(reverse) relationship: grades

Of course, what's "forward" and what's "reverse" it purely semantics.

A: If I am assuming it right, for each class, student has a grade. If that is the case then you should have student_class and student_class_grade models. student_class ---one to many---student_class_grade.

A: The complete answer, thanks to all the comments above and also atomicbird #iphonedev irc channel:
To add the same student to different classes and have or edit the student's grade pertaining to each class: the model is:


text:
Q: Swift macOS how to disable menubar button I'm trying to disable the undo and redo buttons in my macOS app. I selected each button and unchecked "enabled" in the attributes inspector, and yet the buttons are still enabled. I discovered that when I remove the IBActions I have associated with each button, then they become disabled. But I need the IBActions. Ultimately, I need to programmatically determine whether the buttons are enabled. How do I do that?

A: You have to conform your controller, having those actions to NSUserInterfaceValidations and provide implementation for
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
   if item.action == #selector(your_action_here) {
      return // your condition condition for enable/disable
   }
   return false
}

Alternate is NSMenuItemValidation, but above is more generic.
Related documentations: User Interface Validation


text:
Q: Set and merge 'in-place': could it cause problems? I have a static member variable and I set its values like so:
    private static $HTML_FILTER = [
        'div' => ['aria' => 1]
    ];

    public function __construct($allowed_html) {
        // Is the below dangerous?
        MyClass::$HTML_FILTER = array_merge_recursive(allowed_html, MyClass::$HTML_FILTER);

        // Should I instead do
        $temp = array_merge_recursive(allowed_html, MyClass::$HTML_FILTER);
        MyClass::$HTML_FILTER = $temp;
    }

Essentially I am interrogating a static array right before I (over)write it. Would this cause issues on certain versions of PHP or all?


text:
Q: fluent nhibernate query taking a long time to sort a mapped formula with paging We have a data grid to display member records for our clients. We recently were tasked to add paging to our application so that our large clients (500,000+ members).
Our table that we grab the data from has 10 columns. When pull our data into our application we added 3 additional columns that are all calculated fields
i.e.
SELECT SUM(tableX.Cost) FROM tableX WHERE tableX.ID = this_.ID

where "this_" is the alias for our members table and tableX represents the other table that we need to grab data from.
In our query we must provide the ability to order the columns, but i've noticed that when I try to order the calculated fields that it takes a significant amount of time compared to when I ORDER BY an column that exists in the table. This makes sense that it takes longer, but when it takes a couple minutes to load only 1000 records and there will be 500+ pages to go through. Then I feel this makes paging pointless.
I've looked a bit into maybe doing a 2nd level cache with nhibernate, but from what i've read so far i'm not sure if will solve this problem.
By the way one of the maps is:
Map(x => x.Cost)
    .Formula(@"(SELECT SUM(_Claims.Cost) FROM _Claims WHERE _Claims.ID = this_.ID")
    .Nullable();

and for the query
    var list = CurrentSession()
               .SetFirstRsult(startPos)
               .SetMaxResults(1000)
               .SetTimeout(100)
               .Add(Restrictions.Eq("ClientID", _clientID));

    if(isASC)
    {
        list.AddOrder(Order.Asc(Projetions.Property(_propertyString)));
    }
    else
    {
        list.AddOrder(Order.Desc(Projetions.Property(_propertyString)));
    }

    return list.List<Member>();

I'm running out of ideas for this. So if anyone can point us in the right direction I'd appreciate it a lot.
Thanks

A: This is actually not so much a NHibernate problem, but a general SQL problem.
Of course it is sorted on the server, but the sum will be calculated for all the records before they can be sorted. You should be able to verify that by using an SQL profiler or by creating an SQL function / procedure that calculates the sum and insert that into your query and then check how often it is called. If you have a table with 500,000+ members it will be called 500,000+ times; there is just no way around it.
What you could try is this:

*

*Make sure you use an index on Claims.ID (a foreign key does the trick).

*Copy&Paste the generated SQL and run it directly on the database and see whether that takes a long time.

*If you don't mind having some form of redundancy you can add new columns for the calculated fields in your Members table and use triggers (insert/delete) on the Claims table to update those columns accordingly.

*If you don't want to use triggers you could also create a scheduled database event to do the calculation. (Of course, that will only be an option if you don't need real-time data).

A: *

*The first option would be to precompute the data and have them ready to be queried from a table

*Create a view and map it to a Data Transfer Object. In the view you can first constrain the dataset and then do the calculation. Less data to do calculation makes your query execute faster.


text:
Q: I want to specify that on following area on google map we have a coverage I want to do this on android app Hello guys I am new in android.
http://www.att.com/maps/wireless-coverage.html
open this link and see a image of  coverage area of map
I want to do same thing in on android app ,I want to do draw same coverage area on map in android app  I am using google map api v2 in android app.
Thanks


text:
Q: Internet Explorer incorrectly calculates percentage height for generated content in td IE11 is calculating the height of a table cell as the height of its content (20px) and not as the height of its background (100px).
Other browsers work as expected.
How can I fix that in IE?
Or: what am I doing wrong?
Or: how can I work around that?

I need this so I can draw a vertical line behind a table cell.
1. Restrictions
Some work-arounds are not possible, due to the details of my particular problem.
1.A. Height is not constant
The height is not constant, it depends on the amount of text on another cell.
So I cannot use a fixed line-height either. If I could, I could also just put that fixed size as ::before's height.
1.B. Cannot use a background-image
I cannot work around that  by using a repeating background-image because the line is supposed to not be drawn behind an icon that is centred, so I am drawing it by using generated content (::before and ::after) with height: calc(50% - 20px);.
2. Online sample
Try opening the online sample in IE11, and in Firefox or Chrome.
Note that JavaScript shows the first cell to be 100px tall, and the background fills the 100px. But the generated content is only ~20px tall...
<!DOCTYPE html>

abc	def

A: Internet Explorer content height is related to closest element with height set in absolute units, such as pixels.
If you want to use % height, you need to set the height on all parent elements, this will be html, body, table ....
Cause this is not possible for you, use this trick to meets your requirements.

"use strict";
var borked = document.getElementById("borked");
var td = document.createElement("td");
td.textContent = "(1st cell seems to be " + borked.clientHeight + "px tall)";
borked.parentElement.appendChild(td);
#borked {
    background: yellow;
    position: relative;
    height: 100%;
    overflow: hidden;
}
#borked~* {
    height: 100px;
}
#borked::before {
    content: "";
    position: absolute;
    top: 0;
    width: 100%;
    margin: -99999em;
    padding: 99999em;
    background-color: rgba(0, 255, 0, 0.3);
}

abc	def


text:
Q: Action Button showing up but not overflow menu in Android actionbar I am a new developer and trying to show action buttons and overflow menu. 4/6 buttons show in actionBar but i cant see overflow menu with other buttons. Following is the code
res/menu/menu/menu_activity_action.xml
<menu  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myapp="http://schemas.android.com/apk/res-auto" >
    <item
        android:id="@+id/phone"
        android:title="@string/phone"
        android:icon="@drawable/phone"
        and
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/computer"
        android:title="@string/computer"
        android:icon="@drawable/computer"
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/gamepad"
        android:title="@string/gamepad"
        android:icon="@drawable/gamepad"
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/camera"
        android:title="@string/camera"
        android:icon="@drawable/camera"
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/video"
        android:title="@string/video"
        android:icon="@drawable/video"
        myapp:showAsAction="ifRoom|withText"
    />

    <item
        android:id="@+id/email"
        android:title="@string/email"
        android:icon="@drawable/email"
        myapp:showAsAction="ifRoom|withText"
    />
</menu>

mainActivity :
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_activity_action,menu);
        return super.onCreateOptionsMenu(menu);
    }

Any idea ??

A: Try changing to:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_activity_action, menu);

    return true;
}

A: @Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_activity_action, menu);
    return true;
}


text:
Q: Environment.NewLine sometimes returns \n Linefeed instead of \r\n Carriage Return, Line Feed I'm displaying an address to a user on a ASP.Net page using a label. The new lines are converted from
Environment.NewLine

to

If a user edits the address, the address is displayed in a text area and the

is replaced with
Environment.NewLine

Sometimes the address saved to the database only has the line feed. Given how often this happens, it looks like it could be happening for Linux or OSX users.
Does Environment.NewLine return the new line value of the client's browser or of the server, or could it something else?

A: No, Environment.NewLine returns whatever's on your server (because that's where it's running). It's entirely possible that a browser running on Unix will submit data with just "\n" instead of "\r\n" as the line-break. It sounds like you should be normalizing the data before saving it in the database. Then you know you can perform the replacement to
 safely for display purposes.
(I'm assuming your server is running on Windows, and that that's where all your code is - i.e. there's no Silverlight etc involved.)


text:
Q: How can one use Active Directory authentication without requiring the user to enter a domain name? Right now I have Active Directory authentication working on a web application. Users login with their AD credentials. They have to enter their ad credentials like:

myname@ourdomain.com

I'd like for them to be able to enter their ad credentials like:

myname

Is this possible? If so, how?

A: Here is what I did as a work around
change your login control into template
and then add this code
 Protected Sub LoginButton_Click(sender As Object, e As System.EventArgs)
    If Not UCase(LoginUser.UserName).EndsWith("@MYDOMAIN.LOCAL") Then
        LoginUser.UserName &= "@MYDOMAIN.local"
    End If
End Sub

OR
on your web.config add :
       attributeMapUsername="SAMAccountName" to your provider

so it looks like
 <membership defaultProvider="MyADMembershipProvider">
  <providers>
    <add
       name="MyADMembershipProvider"
       type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
       connectionStringName="ADConnectionString"
       connectionUsername="MYDOMAIN\administrator"
       connectionPassword="MYPASSWORD"
       enableSearchMethods="true"
       attributeMapUsername="SAMAccountName"/>
  </providers>
</membership>


text:
Q: NO graph results with jmeter I have installed jmeter based on tutorial in guru99.com and now following exactly the steps from https://www.guru99.com/jmeter-performance-testing.html page but get no graph results .
I open jmeter in gui mode cause in the command line mode I get error could not open testPlan.jmx

A: You forgot to add HTTP Request which will send the request

Right-click on Thread Group and select: Add -> Sampler -> HTTP
  Request.

A: I followed the same tutorial, I am using jmeter4, initially, I faced the same issue, then I tried importing the following suite, I did the following,
Check whether you are connecting to the internet via a proxy. If yes, remove the proxy.
    Open a new instance of Jmeter
    Open the PerformanceTestPlan.jmx in Jmeter
    Double Click on Thread Group -> Graph Result
    Run the Test

URL: https://www.guru99.com/jmeter-performance-testing.html

A: You should set number of users enough to be visible on your graph and on your picture there's no HTTP Requests. In my case I've set number of users equal 20 in my Thread Groups with Ramp-Up period equal 60.
Also I've:

*

*added HTTP Request Defaults, HTTP Header Manager and Graph Results in the root of my Test Plan

*added two Thread Groups in the root of my Test Plan

*added 20 different HTTP Requests in both Thread Groups

*added View Results listeners in both Thread Groups


text:
Q: Constructing a 3D cube of points from a list I have a list pts containing N points (Python floats).  I wish to construct a NumPy array of dimension N*N*N*3 such that the array is equivalent to:
for i in xrange(0, N):
    for j in xrange(0, N):
        for k in xrange(0, N):
            arr[i,j,k,0] = pts[i]
            arr[i,j,k,1] = pts[j]
            arr[i,j,k,2] = pts[k]

I am wondering how I can exploit the array broadcasting rules of NumPy and functions such as tile to simplify this.

A: I think that the following should work:
pts = np.array(pts)  #Skip if pts is a numpy array already
lp = len(pts)
arr = np.zeros((lp,lp,lp,3))
arr[:,:,:,0] = pts[:,None,None]  #None is the same as np.newaxis
arr[:,:,:,1] = pts[None,:,None]
arr[:,:,:,2] = pts[None,None,:]

A quick test:
import numpy as np
import timeit

def meth1(pts):
   pts = np.array(pts)  #Skip if pts is a numpy array already
   lp = len(pts)
   arr = np.zeros((lp,lp,lp,3))
   arr[:,:,:,0] = pts[:,None,None]  #None is the same as np.newaxis
   arr[:,:,:,1] = pts[None,:,None]
   arr[:,:,:,2] = pts[None,None,:]
   return arr

def meth2(pts):
   lp = len(pts)
   N = lp
   arr = np.zeros((lp,lp,lp,3))
   for i in xrange(0, N):
      for j in xrange(0, N):
         for k in xrange(0, N):
            arr[i,j,k,0] = pts[i]
            arr[i,j,k,1] = pts[j]
            arr[i,j,k,2] = pts[k]

   return arr

pts = range(10)
a1 = meth1(pts)
a2 = meth2(pts)

print np.all(a1 == a2)

NREPEAT = 10000
print timeit.timeit('meth1(pts)','from __main__ import meth1,pts',number=NREPEAT)
print timeit.timeit('meth2(pts)','from __main__ import meth2,pts',number=NREPEAT)

results in:
True
0.873255968094   #my way
11.4249279499    #original

So this new method is an order of magnitude faster as well.

A: import numpy as np
N = 10
pts = xrange(0,N)
l = [ [ [ [ pts[i],pts[j],pts[k] ]  for k in xrange(0,N) ] for j in xrange(0,N) ] for i in xrange(0,N) ]
x = np.array(l, np.int32)
print x.shape # (10,10,10,3)

A: This can be done in two lines:
def meth3(pts):
    arrs = np.broadcast_arrays(*np.ix_(pts, pts, pts))
    return np.concatenate([a[...,None] for a in arrs], axis=3)

However, this method is not as fast as mgilson's answer, because concatenate is annoyingly slow. A generalized version of his answer performs roughly as well, though, and can generate the result you want (i.e. an n-dimensional cartesian product contained within an n-dimensional grid) for any set of arrays.
def meth4(arrs):     # or meth4(*arrs) for a simplified interface
    arr = np.empty([len(a) for a in arrs] + [len(arrs)])
    for i, a in enumerate(np.ix_(*arrs)):
        arr[...,i] = a
    return arr

This accepts any sequence of sequences, as long as it can be converted into a sequence of numpy arrays:
>>> meth4([[0, 1], [2, 3]])
array([[[ 0.,  2.],
        [ 0.,  3.]],

       [[ 1.,  2.],
        [ 1.,  3.]]])

And the cost of this generality isn't too high -- it's only twice as slow for small pts arrays:
>>> (meth4([pts, pts, pts]) == meth1(pts)).all()
True
>>> %timeit meth4([pts, pts, pts])
10000 loops, best of 3: 27.4 us per loop
>>> %timeit meth1(pts)
100000 loops, best of 3: 13.1 us per loop

And it's actually a bit faster for larger ones (although the speed gain is probably due to my use of empty instead of zeros):
>>> pts = np.linspace(0, 1, 100)
>>> %timeit meth4([pts, pts, pts])
100 loops, best of 3: 13.4 ms per loop
>>> %timeit meth1(pts)
100 loops, best of 3: 16.7 ms per loop


text:
Q: Cannot get simple_nested_form to submit data I am trying to build a simple_nested_form in my Ruby on Rails app.  When I submit my form I am getting some unknown error because it is just redirecting back to the form to input again.  Here is the output in the rails server console for when I submit the form.  It looks like there is some random "0" => thrown in there.
Parameters: {"machine"=>{"name"=>"2134", "ip_adress"=>"2", "machine_employees_attributes"=>{"0"=>{"machine_id"=>"1", "employee_id"=>"2"}}}, "commit"=>"Create Machine"}

I have a machine model which has_many :machine_employees
and a machineemployee model which belongs_to :machine
Do you have any idea why this 0 => could be appearing because I think it is what is giving me the issues.
Here is the code for my models.
Machine
class Machine < ActiveRecord::Base

# Relationships
has_many :machine_employees
has_many :employees, :through => :machine_employees

accepts_nested_attributes_for :machine_employees, :reject_if => lambda{ |me| me[:employee_id].blank? }

attr_accessible :ip_adress, :name, :machine_employees_attributes

# Validations
validates_presence_of :name, :ip_adress
end

MachineEmployee
class MachineEmployee < ActiveRecord::Base
before_validation :set_default

# Relationships
belongs_to :machine
belongs_to :employee

attr_accessible :employee_id, :machine_id, :end_date, :start_date

# Validations
validates_presence_of :employee_id, :machine_id, :start_date

private

# Callback Methods
def set_default
  self.start_date = Date.today
  self.end_date = nil
end

end

New Machine Form

Add a Machine

    <%= simple_nested_form_for @machine do |f| %>
        <%= render "machine_fields", :f => f %>
        <%= f.button :submit %>
        <%= link_to 'Back', machines_path %>

Assign an Employee to This Machine

    <%= f.simple_fields_for :machine_employees do |me_form| %>

        <%= render "machine_employee_fields", :f => me_form %>
    <% end %>

<% end %>

Machine Employee Fields Partial
<%= f.input :machine_id, :as => :hidden, :input_html => { :value => @machine.id } %>
<%= f.input :employee_id, collection: @employees, :id => :name, :prompt => "Select ..." %>

A: The 0 is thrown in there because the machine model has_many machine_employees. When you use nested forms, it passes a pseudo-array for has_many relations. So, if you tried to submit 2 machine employees, your hash would look like this:
Parameters: {"machine"=>{"name"=>"2134", "ip_adress"=>"2", "machine_employees_attributes"=>{
                           "0"=>{"machine_id"=>"1", "employee_id"=>"2"},
                           "1"=>{"machine_id"=>"1", "employee_id"=>"3"}
                        }
            }, "commit"=>"Create Machine"}

This way you can access the machine_employees passed from the form by doing params[:machine][:machine_employees_attributes][0] or params[:machine][:machine_employees_attributes][1]. Note that if this was a has_one relationship, then the machine_employees_attributes key would be changed to machine_employee_attributes and there would be no numerical index.
I suspect the problem is that your machine model must accept_nested_attributes_for :machine_employees and must also have attr_accessible :machine_employees_attributes.


text:
Q: Do i need to declare an array if i want to assign another array to it? I have a small question. Do i need to declare an array if i want to assing another array to it?
I want to validate the values from a multiple select control, and i need them to be in an array (for sticky form fields)... i don't remember if in php, i can just assign the select array to a var and the var will become an array automatically or the var needs to be declare first as an array...
I've tried both methods, and it looks to me that both work ok. But, for good practices, i want to make sure... i need to know from the experts!
What do you think?
<select name="genre[]" multiple="multiple" id="genre">
   <option value="...">value goes here</option>
</select>

// genres
if (isset($_POST['genre'])) {
  $selected_genre = $_POST['genre'];
}

or
// genres
$selected_genre = array();

if (isset($_POST['genre'])) {
  $selected_genre = $_POST['genre'];
}

A: Quick answer, when you set a variables value as an array, it is an array. Longer answer in safe_mode you get warnings for undefined indexes, and in OOP (object oriented programming) in some cases yes. And generally it is better practice to define variabled before use

A: Technically, no. However, it makes it easier later, so you don't need is_array calls to verify that there's something assigned.


text:
Q: Does a flame put off a windlike force When I hold a flame above a flame the one on top flickers and waves as if its about to go out. What is the cause of this?

A: Flame produces hot gas flowing upwards and blowing the flame on top.

A: Likely, the top flame is being robbed of its oxygen by the bottom flame.


text:
Q: Android - instead of launch new intent to new class/activity, how go back to open activity/class? My code allows me to launch a new activity/class:
Intent intent = new Intent(activity1.this, activity2.class);
startActivity(intent);
finish();

What if i have an activity already open, and just want to go back to it instead of reopening a new one, thus having multiple open of same.. So i want to switch back to an already open activity/class ?

A: Intent intent = new Intent(activity1.this, activity2.class);
intent .setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

A: It's the same thing. Android OS doesn't create 2 different versions of your activity, it works with already created activities.

A: Really simple:
finish();

If you want to choose an already existing activity in the backstack and not simply the latest opened that will be more complex and I don't know if you can modify the normal application workflow

A: Add this
FLAG_ACTIVITY_REORDER_TO_FRONT to your Intent you use with startActivity() .

Also remove finish()

A: If I'm getting you right, you need to use Intent.FLAG_ACTIVITY_REORDER_TO_FRONT flag. In this case your activity, if it was created before, will be brought to the front. As documentation states,

If set in an Intent passed to Context.startActivity(),
  this flag will cause the launched activity to be brought
  to the front of its task's history stack if it is already running.


text:
Q: How to install compiler and binutils on FreeNAS? I'd like to run a backup tool, duplicity, that apparently requires a cc compiler and binutils.  I'm able to locate and install the required BSD packages for python, gcc, and dependencies from ftp2.freebsd.org.  However, I can't find binutils.
How are binutils installed on a system like FreeNAS?  I'm working with FreeNAS 0.70 (based on FreeBSD 7.2).  I see several packages with binutils in the name, but it's not clear any of them are for my i386 platform.
e.g. I see i386-rtems-binutils-2.19.1, but I can't find any info that suggests this is correct for my platform.  Google results mention it's for realtime systems.

A: There is an extensive howto on how to get gcc and binutils running on a FreeBSD System at http://www.freebsd.org/doc/en/articles/custom-gcc/article.html As you say FreeNAS is based on FreeBSD, this probably applies here, too. But keep in mind, that compiling complex software on an embedded system isn't much fun. Probably you will have more success by setting up a cross-compiler on your main system and compile there the software for you FreeNAS system. See http://www.productionmonkeys.net/guides/freenas/building-freenas for a howto on this.


text:
Q: Is there a naming convention for nested "const" JavaScript values? How would we or should we carry over Java or other C-like casing conventions for constants to JavaScript?
In Java we would name a "constant" (static final) member with ALL_UPPERCASE.  If we had a set of values we wanted as constants, we could use an enum member, and we'd name the enum member with a HumpBack name, but the seperate enum's would be UPPERCASE, e.g. SomeClass.SomeEnum.SOME_VALUE.
So lets say I have a JavaScript library used for some Star Trek game (picking a silly example), with a root namespace object StarTrek.  I've got some constant values (never mind that Js has no constants) I want to build in for alien species, attributes of planets.  Without thinking about the Java conventions, I'd have went for something like:
StarTrek.SPECIES = {
    HUMAN: "HUMAN",
    KLINGON: "KLINGON",
    VULCAN: "VULCAN"
};

StarTrek.PLANET_ATTRIBUTE = {
    CLASS: {
        M: "M",
        T: "T",
        ...
    },
    LIFE_FORMS: {
        NONE: "NONE",
        INTELLIGENT: "INTELLIGENT",
        NO_INTELLIGENT: "NO_INTELLIGENT"
    }
};

Note that unlike Java, we have something that is like a nested "enum" here in the PLANET_ATTRIBUTES.  I've went for uppercase "enum" names here because it feels like everything below StarTrek. is essentially supposed to be "constant" (vs in Java where the enum is actually a Class, hence the BumpyCase name).  So anyway I could specify that there where no intelligent lifeforms by using StarTrek.PLANET_ATTRIBUTE.LIFE_FORMS.NO_INTELLIGENT.
Now, following Java's conventions I would have gone with something like:
StarTrek.Species = {
    HUMAN: "HUMAN",
    KLINGON: "KLINGON",
    VULCAN: "VULCAN"
};

StarTrek.PlanetAttribute = {
    Class: {
        M: "M",
        T: "T",
        ...
    },
    LifeForms: {
        NONE: "NONE",
        INTELLIGENT: "INTELLIGENT",
        UNINTELLIGENT: "UNINTELLIGENT"
    }
};

In which case I would specify that there where no intelligent lifeforms by using StarTrek.PlanetAttribute.LifeForms.NO_INTELLIGENT.
Which fits JavaScript better and why?  Are there any conventions proposed for this?

A: The answer is: it really doesn't matter (at all)!
The second convention looks better (first one shouts at you) and is used in C# too, but it depends on you! I think there is no restrictions about this.
But about enums values in javascript: maybe this would be better? You can use your enums as flags.
StarTrek.Species = {
    HUMAN: 1,
    KLINGON: 2,
    VULCAN: 4
}

Edit:
As Jason said, in javascript there is not any concept of constants, so it depends on your choice.


text:
Q: Twenty Twelve theme: remove margins Maybe this is too simple question, but I've tried to find out the info by myself.
How can I remove margins (all: left, top, right, bottom) for Twenty Twelve theme?
This is what I mean:

A: I think you mean these class definitions in style.css:
    /* =Media queries
    -------------------------------------------------------------- */

    /* Minimum width of 600 pixels. */
    @media screen and (min-width: 600px) {

    ...cut...

        .site {
            margin: 0 auto;
            max-width: 960px;
            max-width: 68.571428571rem;
            overflow: hidden;
        }

    ...cut...

    }

  /* Minimum width of 960 pixels. */
  @media screen and (min-width: 960px) {

    ...cut...

    body .site {
        padding: 0 40px;
        padding: 0 2.857142857rem;
        margin-top: 48px;
        margin-top: 3.428571429rem;
        margin-bottom: 48px;
        margin-bottom: 3.428571429rem;
        box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3);
    }

    ...cut...

}

Edit:
Here is a style.css for a child theme:
/*
Theme Name:     Twenty Twelve Child
Theme URI:      http: //example.com/
Description:    Child theme for the Twenty Twelve theme
Author:         birgire
Template:       twentytwelve
Version:        1.0
*/

@import url("../twentytwelve/style.css");

/*-----------------
Custom page layout
-------------------*/

/* remove site margin */
body .site{margin:0;max-width: 100%;}


text:
Q: How to retain the pagination number, after reloading the page I am using Angular PrimeNG Paginator Component (i.e p-paginator).
The HTML part of the code looks like :
<div class="paginator paginator-product mb-5">
        <p-paginator [rows]="12" pageLinkSize="6" [alwaysShow]="false" [showCurrentPageReport]="true"
          [totalRecords]="totalRecords" #paginator (onPageChange)="onPageChange($event)"></p-paginator>
      </div>

Here the issue is that, suppose current page is on 6th index, when I am reloading the page, it gets back to 1 (the position of the page is not retaining)

Is there any way, that I can retain the page number even after reloading the page OR make the paginator to get selected at a particular index.

A:  <p-paginator [rows]="1" [first]="6" [alwaysShow]="false" [showCurrentPageReport]="true"
      [totalRecords]="totalRecords" #paginator (onPageChange)="onPageChange($event)"></p-paginator>


text:
Q: angular2 debugging: breakpoint not getting hit at execution only at initialization I'm trying to debug my angular2 app with source map by placing a breakpoint in the .ts file.
foo(){
   //breakpoint here
   console.log('bar');
 }

the breakpoint only gets hit when loading that component and not when executing.
any idea?

A: put debugger; in the line where ever you want.browser will definitely pauses;

A: Not sure if you still need an answer, but assuming you're doing something like this, I believe angular runs some code only once (like constructors / initialization ... etc).
If the break point is only getting hit once, it is probably because angular intends for that. Try putting your breakpoint in a method that you know for sure gets called multiple times. Try to figure out [where your code is](https://angular.io/docs/ts/latest/guide/architecture.html#!#components in the bigger picture of the architecture of an angular app.
Otherwise, would need more context/info to properly answer.

A: Closing and opening the browser, solved my issue.


text:
Q: String matching in Peewee (SQL) I am trying to query in Peewee with results that should have a specific substring in them.
For instance, if I want only activities with "Physics" in the name:
schedule = Session.select().join(Activity).where(Activity.name % "%Physics%").join(Course).join(StuCouRel).join(Student).where(Student.id == current_user.id)

The above example doesn't give any errors, but doesn't work correctly.
In python, I would just do if "Physics" in Activity.name, so I'm looking for an equivalent which I can use in a query.

A: You could also use these query methods: .contains(substring), .startswith(prefix), .endswith(suffix).
For example, your where clause could be:
.where(Activity.name.contains("Physics"))

I believe this is case-insensitive and behaves the same as  LIKE '%Physics%'.

A: Quick answer:
just use Activity.name.contains('Physics')

Depending on the database backend you're using you'll want to pick the right "wildcard".  Postgresql and MySQL use "%", but for Sqlite if you're performing a LIKE query you will actually want to use "*" (although for ILIKE it is "%", confusing).
I'm going to guess you're using SQLite since the above query is failing, so to recap, with SQLite if you want case-sensitive partial-string matching: Activity.name % "*Physics*", and for case-insensitive: Activity.name ** "%Physics%".
http://www.sqlite.org/lang_expr.html#like


text:
Q: How replicate label in prometheus metric The metric kube_pod_container_resource_requests_cpu_cores from kube-state-metrics comes with the labels:
kube_pod_container_resource_requests_cpu_cores{app="prometheus",chart="prometheus-8.1.0",component="kube-state-metrics",container="autoscaler",heritage="Tiller",instance="10.233.65.93:8080",job="kubernetes-service-endpoints",kubernetes_name="prometheus-kube-state-metrics",kubernetes_namespace="kube-system",kubernetes_node="k8st01",namespace="kube-system",node="k8snode",pod="kubedns-autoscaler-5db95c6cf5-cvqz4",release="prometheus"}

I want to make another label pod_name from pod , with the same values. In the end i want to have both pod="kubedns-autoscaler-5db95c6cf5-cvqz4" and pod_name="kubedns-autoscaler-5db95c6cf5-cvqz4"
I used the followimng
relabel_configs:
  - source_labels: [pod]
    target_label: pod_name

but it didn't work.

A: Try to use metric_relabel_configs. Your config block would look something like this:
metric_relabel_configs:
  - source_labels: [pod]
    target_label: pod_name


text:
Q: How to increase google custom search quota for image search beyond 10000? The app I work on has previously used the Google Image Search API to allow users to search for images to use in their document. The API has been deprecated for a long time, and google finally pulled the plug on it, which meant that we had to move to its supposed replacement, custom search.
There is now a maximum of 10000 requests per day per app. We reach that quota in about half a day (apparantly users really like our google image search integration). We have contacted multiple contacts at google, and looked for any documentation on getting a higher quota without any luck.
Also, users seem to start getting 403s saying that the limit is exceeded even before we have reached the quota.
Does anyone know how we can increase our quota above 10000, or why we are getting throttled before we reach the limit?  Alternatively, does anyone know of a better fit for replacing Google Image Search API? We do want it to be Google image search, so not bing or yahoo or something like that.

A: Currently, you can't, at least not via any official channel. You used to be able to "Request more", but it was removed. Even when it was present, I'm not sure how often Google actually increased the limit.
If you need to do more than 10k searches per day, consider using another search engine with better API limitations, e.g. Bing, which offers up to 20m requests per month at $0.002 per request.
The only other workaround is to create multiple Google API projects, and round robin your requests among them.


text:
Q: Page not index in google search console I recently try to Index 10,000 pages in google search console but it is more than 2 week these pages still not index someone please help me to fix this problem.
Or share any method to index page Quickly.
The site is: https://www.solutioninn.com/

A: As I can see that your website is made in AngularJs version 1. Now, there is hell lots of issues with Angularjs version 1 and Google indexing.
Google bot uses Chromium version 41 to crawl and index websites for the search engine. For having a clear understanding that where your website is failing to get indexed, Download Chromium/Chrome browser version 41 and then load your website and check what errors you are getting in the console. If you are getting a single error your site will not get indexed. You also need to implement proper meta tags.
I have worked extensively on this type of issues. It would be really terrible to write a whole solution here. You can ping me in person. I may help in resolving your issue.


text:
Q: Can I make a model know about its ModelForm? I have a standard Model and ModelForm set-up. I want to be able to return the ModelForm object from my Model. This involves an impossible circular reference. I thought that since Django allows foreign key models to be expressed as strings, perhaps it's possible to do something similar. At the moment I'm doing this:
class Thing(models.Model):
    stuff = models.TextField()

    def get_form(self):
        return getattr(sys.modules[__name__], "ThingForm")(self)

class ThingForm(ModelForm):
    class Meta:
        model = Thing

It works. But I feel that in doing this I bring shame upon myself and my family. There must be a more honourable way.
By the way, I want do to this because I'm using ContentTypes to create generic foreign keys, so my view code doesn't know what class the model is in the static context.

A: That's... not an impossible circular reference. Names are only looked up when the code that references them is run.
class Thing(models.Model):
    stuff = models.TextField()

    def get_form(self):
        return ThingForm(self)

class ThingForm(ModelForm):
    class Meta:
        model = Thing


text:
Q: Is Java Metro mandatory for calling WCF? Why would jaxws not enough as Metro is not well known and so would require a new learning curve for the dev team: what benefits do metro add ?

A:
Is Java Metro mandatory for calling WCF?

No.  Firstly, you can (in theory) implement interoperability yourself, though it is apparently difficult.  Secondly, Microsoft have apparently released Java bindings for WCF interoperability on Codeplex:
Reference:  Microsoft Releases Java-Friendly Interop Bindings for WCF Services
I cannot tell you whether the Metro approach or the MS bindings will be better.

And the flipside is that WCF is not mandatory for using Java Metro either
"Note: Because Metro-based clients and services are interoperable, you can gain the benefits of Metro without using WCF."
Reference: Metro User Guide: Chapter 1.3

Why would jaxws not enough

In theory it is.  In practice, it will be less work to use existing bindings (Metro or MS) than to dredge through the specs, etcetera to figure out how to implement the bindings and make them actually work.  Of course, the amount of work will depend on how much of WCF you needed to use.  But reinventing the wheel is usually a bad idea ...


text:
Q: How to separate a line into an array with white space in shell scripting I can't figure out why my script is not displaying the string separated by white space.
This is my code:
While read -r row
do

   line = ($row)
   for word in $line
   do
       echo ${word[0]}
   done
done < $1

say the line is "add $s0 $s0 $t1"
 i want the output to be "add"

A: While read -r row

This will try to run a command called While, you'll probably get an error for that. The shell keyword is while.
do
   line = ($row)

This will try to run a command called line, which is a program from GNU coreutils (line - read one line), but probably not what you want. Assignments in the shell must not have whitespace around the equal sign.
If that assignment worked, it would make an array called line.
   for word in $line

Referencing the array just by name expands to the first item of it, so the loop is useless here.
   do
       echo ${word[0]}

And here, indexing is not very useful since word is going to be a single value, not an array.
I suspect what you want is this:
while read -r row ; do
    words=($row);
    echo "${words[0]}"
done

Though if $row contains glob characters like *, they'll be expanded to matching filenames.
This would be better:
read -r -a words
echo "${words[0]}"

or simply
read -r line
echo "${line%% *}"     # remove everything after the first space

A: This work fine :
while read -r row
do
  echo $row | awk '{print $1}'
done

while read -r row ask for user input and store it in row variable, awk '{print $1}' display only first word of user input.

A: Do you want each token on a seperate line? Why not just use sed?
$ echo "1 2 3 hi" | sed -r 's/[ \t]+/\n/g'
1
2
3
hi

If you want the first word of each line, then:
$ echo "1 2 3 hi" | sed -r 's/^([^ \t]+).+/\1/'
1

If its a file, then remove "echo ... | " and just give the filename as a parameter to sed:
$ sed -r 's/^([^ \t]+).+/\1/' file.txt


text:
Q: Qual a diferença ao chamar uma função com parênteses e sem no urls.py com Django 1.7? No mapeamento do meu urls.py eu utilizo desde funções comuns até views baseadas em classes.
Quero saber qual a diferença de chamar a view com ou sem parênteses, tendo em vista que se eu tenho a entrada url(r'^$', base_views.index_view), colocar os parênteses ao chamar a função correspondente (que na declaração recebe apenas um objeto request) lança um TypeError com a seguinte mensagem: index_view() missing 1 required positional argument: 'request'.
Já na entrada url(r'^authors/$', AuthorViews.AuthorView.as_view), quando removo os parênteses ele lança o mesmo erro citado acima com a mensagem: as_view() takes 1 positional argument but 2 were given.
Eu entendo que o problema é que ao chamar uma das funções, os argumentos da mesma  não são supridos  como na declaração, mas, não entendo como a função url do Django passa esses parâmetros nem porque os parênteses fazem diferença.

A: Basicamente uma "view" é uma função que recebe uma requisição (resquest) e retorna uma resposta (response).
from django.http import HttpResponse
import datetime

def index_view(request):
    now = datetime.datetime.now()
    html = "It is now %s." % now
    return HttpResponse(html)

As views são então mapeadas no URLConf do Django. Exemplo abaixo:
from django.conf.urls import patterns, url

from . import views

urlpatterns = patterns('',
    url(r'^$', views.index_view, name='principal'),
    url(r'^autores/$', views.AuthorView.as_view(), name='autores')
    ...
)

O Django faz a correspondência entre a url que o usuário acessa e as
expressões regulares das urls na URLConf, executando a "view" que está mapeada de acordo.
Para essa "view" são passados os seguintes argumentos:
1 - Uma instância de HttpRequest.
2 - Argumentos que vem da URL
3 - Argumentos extras opcionais.
A função url() segue o seguinte padrão.
url(regex, view, kwargs=None, name=None, prefix='')

O Django é que fará a chamada da "view" e passará os argumentos corretamente.
Logo você deve passa o callable e não a chamada da função.
"index_view" (callable) é diferente de "index_view(request)".
No tocante a Class Based Views você vai precisar executar o método as_view para
'transformar' sua CBV em uma view. CBView.as_view() retorna um callable.
response = CBView.as_view()(request)

https://docs.djangoproject.com/en/1.7/topics/http/urls/#how-django-processes-a-request
https://docs.djangoproject.com/en/1.7/ref/urls/#url
https://docs.djangoproject.com/en/1.7/ref/class-based-views/base/#django.views.generic.base.View.as_view

A: O que está acontecendo lá dentro do código da função url é algo mais ou menos assim:
def url(regex, view):
    request = make_request()
    view(request)

O parâmetro view é uma função que recebe um request. A função url passa o request para a função view.
Quando você chama o método view sem parâmetros você obtém o erro que você mencionou pois você está passando um parâmetro a menos do que o esperado. Já quando você omite os parênteses você na verdade não está chamando o método, você está apenas criando um "bound method", que é equivalente a você ter escrito
url(r'^$', (lambda req: base_views.index_view(req))

Como você pode ver, não estamos chamando o método view - estamos apenas passando pra função url uma função que chama o view.

A: Quando você associa uma URL a uma view você não está chamando a função da view - apenas indicando qual função deverá ser chamada quando alguém visitar aquela URL. Em outras palavras, ao fazer:
url(r'^$', base_views.index_view)

Você está armazenando, em algum lugar, uma referência para index_view. Essa referência será em algum outro momento (pois aqui nenhuma requisição está sendo feita) chamada passando-se como argumento um request.
Se você tentar chamar essa função nesse momento:

*

*Sem parâmetros não vai funcionar, pois ela espera um request;

*Com um parâmetro do tipo request ela pode funcionar, mas aí ela vai retornar um HttpResponse ou similar - e isso não ajuda nada na hora que as requisições verdadeiras forem feitas (pois é necessário saber qual função chamar nesse momento).

Já no outro caso, AuthorViews.AuthorView é um objeto, não uma função. Não basta usar ele próprio no urls.py, pois é preciso saber qual função chamar durante uma requisição, e é pra isso que serve o as_view - ele retorna uma função apropriada para ser associada àquela URL. É uma função que retorna outra função. Por isso precisa ser chamada.
Se você não chama, o Django acha que ela é que é a view, então tenta chamá-la passando um request. Como ela já é um bound method (pois ao fazer AuthorView.as_view ele "ligou" a função ao seu objeto), o parâmetro implícito self já está setado. O segundo parâmetro - um HttpRequest - é inesperado, daí ele reclama de ter recebido um parâmetro a mais.


text:
Q: adding custom validators in angular2 I have created custom validator(cannotContainSpace) and want to use it template component(postmessage.component) but somehow validator cant see my custom validator class I've created.. here is the compiler message:

usernamevalidator.ts
import {FormControl} from '@angular/forms';

export class UsernameValidator{
    static cannotContainSpace(control:FormControl){
        if(control.value.indexOf('')>=0)
            return {    cannotContainSpace:true };
        return null;
    }
}

postmessage.component.ts
import { Component } from '@angular/core';
import {FormControl,FormGroup,FormBuilder,Validators} from '@angular/forms';
import {UsernameValidator} from '../../validators/usernamevalidator';

@Component({
    moduleId:module.id,
    selector: 'post-message',
    templateUrl: '../../templates/postmessage.component.html'
})
export class PostComponent {
    form : FormGroup;
    constructor(fb:FormBuilder){
        this.form = fb.group({
            username:['', Validators.compose([Validators.required, Validators.cannotContainSpace])],
            email:['', Validators.required],
            message:['', Validators.required]
        });
    }
    signup(){
        console.log(this.form.value);
    }
 }

A: username:['', Validators.compose([Validators.required, Validators.cannotContainSpace])],

should be
username:['', Validators.compose([Validators.required, UsernameValidator.cannotContainSpace])],

The Validators class only provides validators that are defined in the Validators class.


text:
Q: Replace word with lowest cost ,Jellyfish python I have an entire list of words with the correct spellings called ref.txt . i have a list of sentences and i have managed to extract words from them using regex. i'll elaborate it with an example .
suppose ref.txt contains - Mumbai , Andheri ,Jacob Circle, Bandra .
I have a list of sentences like -
['Blue Meadows near andhri ', 'Oberoi Heights opp windy road off Bnadra' ,
'Red Heavens club ,behind Mumbia club near Jacob Circle']

there isnt much documentation about jellyfish.
import jellyfish as jf
jf.jaro_distance(andhri,andheri)

the problem is , after extraction of the words using regex,how do i compare it with the entire list.. my algorithm should automatically suggest 'andheri' for andhri due to lowest cost..
in case u have some other ideas to implement , plz do reccommend.. thanks

A: Right so by what I've understood, you want your program to suggest the word closest to what is entered by the user. There's no simple method to do this. You'll have to go with character by character comparison. Compare each character in "andhri" with the character of every word in your list. And keep a counter. Preferably, a list of counters would work better for you. Compare each letter in each word in your list with the letters in "andhri" and everytime you get a match, increment that respective counter. Once you are done comparing each character of each word on your list with "andhri", check the counters. The word corresponding to the highest counter should be suggested to the user.


text:
Q: Salesforce DX - Help for data:tree:export I have a dev hub trial org where I have created an account record with the name 'Chaser' and it has an Id of '0011N00001Eam4C'
When I run the following command, I receive 'Query Returned No results'
sfdx force:data:tree:export -q "SELECT Name FROM Account WHERE Id = '0011N00001Eam4C'" -u DevHub -d ../sourceData
However, the strange thing is when I query by Name instead like so:
sfdx force:data:tree:export -q "SELECT Name FROM Account WHERE Name = 'Chaser'" -u DevHub -d ../sourceData
A Account.json file is populated with 1 record in the sourceData folder.
Why won't results come back when I query with the Id condition?
Thank you for your help!


text:
Q: Delete confirmation message in jquery datatables I am using jquery datatables in my asp.net mvc application. I just want to enable confirmation popup when user presses the delete button for particular row. i cant find any solution over the internet that works. below is my script for datatable in razor view.
Razor View Script


text:
Q: Асинхронные запросы на сервер с ID Стоит такая задача.
Есть сервер, доступ к нему осуществляется по IP адресу через HTTP, он запрашивает логин-пароль.
Клиент создает запрос, отправляет JSON объект с этим запросом, сервер обрабатывает этот JSON, делает нужную операцию, возвращает ответ.
Запросов может быть много, и каждому из них присваивается ID. Это нужно для того, чтобы асинхронно закидывать сервер запросами, а потом определять, ответ на какой именно запрос прислал сервер.
Для этого думаю использовать Map. Но не уверен, что это верный подход.
Плюс, не получается создать подключение к серверу - сколько ни копаю, не понимаю, как его сделать. Уже пересмотрел кучу видео, перелопатил форумы...
блок с подключением к серверу тут я не написал, потому что уже несколько вариантов испробовал, и все оно не работает
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;

public class CertexCloudTotalTest {

    public static void main(String[] args) {

        String userName = "*******";
        String userPassword = "********";
        String serverAddress = "********";

        Map<Integer, req> requestsWithIDs = new HashMap<Integer, req>();

        try {
            URL conn = new URL(serverAddress);
            URLConnection connection = conn.openConnection();

        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public static int generateID () {
        Random random = new Random();
        return random.nextInt();
    }

}


text:
Q: Convert a list with non-fixed length elements to tensor It seems that I can't convert a list with non-fixed length elements to tensor.For example, I get a list like [[1,2,3],[4,5],[1,4,6,7]],and I want to convert it to a tensor by tf.convert_to_tensor, and It doesn't work and throw a ValueError: Argument must be a dense tensor: [[1, 2, 3], [4, 5], [1, 4, 6, 7]] - got shape [3], but wanted [3, 3].I don't want to pad or crop the elements for some reasons, is there any method to solve it?
Thanks in advance!

A: Tensorflow (as far as I know) currently does not support Tensors with different lengths along a dimension.
Depending on your goal, you could pad your list with zeros (inspired by this question) and then convert to a tensor. For example using numpy:
>>> import numpy as np
>>> x = np.array([[1,2,3],[4,5],[1,4,6,7]])
>>> max_length = max(len(row) for row in x)
>>> x_padded = np.array([row + [0] * (max_length - len(row)) for row in x])
>>> x_padded
array([[1, 2, 3, 0],
   [4, 5, 0, 0],
   [1, 4, 6, 7]])
>>> x_tensor = tf.convert_to_tensor(x_padded)


text:
Q: Filtering QUERY_STRING with back references in RewriteCond I have a PHP script used to process images before displaying them on the web page. The query string has to be checked to reject all requests coming from external domains.
If TLD is example.com
http://example.com/process.php?img=somepath/images/imgX.png OK
http://example.com/process.php?img=http://example.com/anotherpath/folder/images/imgX.png OK
http://example.com/process.php?img=http://anotherdomain.com/images/someimg.jpg Rejected!

This rewrite rules work on my test server:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_METHOD} GET
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=http://
RewriteCond expr "! %{QUERY_STRING} -strmatch '*%{HTTP_HOST}*'"
RewriteRule .* - [F]
</IfModule>

But on the production server this doesn't work. After some headaches and searching I found that expr is not supported before Apache 2.4...
From what I read I can use atomic back-references to check if the %{HTTP_HOST} is present in the %{QUERY_STRING}. The idea is to construct something like this
RewriteCond %{HTTP_HOST}::%{QUERY_STRING} ^(.*?)::/\1/?

Which obviously doesn't work in the current state. Any help and further explanation on this syntax will be greatly appreciated.

A: If you wanted to do this in PHP land then you can use parse_url.
Link to PHP documentation.

A: You can use this rule in Apache 2.2:
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=http://
RewriteCond %{HTTP_HOST}#%{QUERY_STRING} !^([^#]+)#.*?\1
RewriteRule ^ - [F]

\1 is back-reference for HTTP_HOST
Modified the RewriteCond to
RewriteCond %{HTTP_HOST}#.*#%{QUERY_STRING} !^([^#]+)#.*?\1

This captures any URL structure. JF


text:
Q: time between applyingchanges event fire and changesapplied event fire I am building an occasionaly connected application using SyncFramework. SQL Server is used in the server-side, SQLCE 3.5 as client-side. As sync providers I'm using DbServerSyncProvider in the server-side and SqlCeClientSyncProvider in the client-side.
Trying to fix some performance issues, I realized that even in case that there are not changes to be applyied in the client, there is a considerable amount of time between applyingchanges - changesapplyied, even if there is no changes to be applied.
Follows some data about these times:

*

*TabelasDeConfiguracaoGroup - SelectingChanges:  SERV

*TabelasDeConfiguracaoGroup - ChangesSelected  SERV  00:00:00,0

*TabelasDeConfiguracaoGroup - ApplyingChanges: 0 changes -  CLIENT   00:00:00,1

*TabelasDeConfiguracaoGroup - ChangesApplied: 0 changes -  CLIENT    00:00:01,1

Interpretation: time between event 1 and 2 is 00:00:00,0 - time between event 2 and 3 00:00:00,1...
As we can see, applying changes is the most wasting operation, even if we don't have any changes to be applyied.
Someone knows why so much time? Is it normal? Is there some way to improve it?
Maybe 1 seconds is not much but I am afraid it will increases as the number of tables increases.
Thanks in advance.


text:
Q: let vs letfn for defining local functions in clojure? When in practice should I use letfn vs. let for defining local functions?
What about cases where I want both local functions and local non-functions?

A: If all I need is one or a few local functions, I letfn them. If I need to define a mix of functions and non-functions, I'll just use a normal let. letfning and leting would be a very verbose way to do this.
However, if you need mutual recursion through your local functions, you'll have to letfn them either way.
Short version: use them when you think it looks better, and when it's convenient. There are no hard and fast rules for using either. They are just tools in the Clojure toolbox.
Have fun!

A: Normally it's easier and neater to use let: that way you can define a set of both functions and non-functions in a single form, and even refer back to previous definitions:
(let [f     (fn [x] ....)
      value (reduce f some-collection)
      foo   bar]
  .....)

letfn is really only needed when you want to define multiple functions that recursively refer to each other. let won't work in this case because it doesn't support recursive references.


text:
Q: Exclude arrow symbol in regex? I have this regex:
r"\]\s*prima\s*1\s*(?!\d+\s+)\S+(?:\s+(?!\d+\b)\S+)*\s*2\s+(?!\d+\b)\S+(?:\s+(?!\d+\b)\S+)*\s*$"

That matches
] prima 1 words 2 words

And excludes 3
However, this also matches:
] prima 1 words → 2 words

How to exclude → ?

A: Try r"\]\s*prima\s*1\s*(?![\d]+\s+)([^\s→]+(?:\s+(?![\d]+\b)[^\s→]+)*)\s*2\s+(?![\d]+\b)([^\s→]+(?:\s+(?![\d]+\b)[^\s→]+)*)\s*$"
demo


text:
Q: javascript prototype overriding a method calls the base method I have three objects extending each other. Base - > A -> childA. They all have a method test in the prototype. When I call A.test or childA.test the Base.test is called. I wonder what are the options each object to call its own method. Here is the code:
$(document).ready(function(){

    function Base(){

    };

    Base.prototype.test = function(){
         console.log("base");
    };

    function A(){

    };

    A.prototype.test = function(){
        console.log("A");
    };

    function ChildA(){

    };

    ChildA.prototype.test = function(){
        console.log("ChildA");
    };

    var base = new Base();

    var a = new A();

    var childA = new ChildA();

    $.extend( a, base );

    $.extend( childA, a );

    a.test();

    childA.test();
}
);

and fiddle: http://jsfiddle.net/pjWjy/84/
So when I call base.test - > log base; a.test -> log a; childA -> log childA;

A: That's not really how you do prototypical inheritance with constructor functions in JavaScript (it's not inheritance at all, just copying methods between instances). With any of the standard inheritance patterns, you'd be getting the right test.
Here's an example:

// On old browsers like IE8, we need to shim Object.create
if (!Object.create) {
  Object.create = function(proto, props) {
    if (typeof props !== "undefined") {
      throw "The second argument of Object.create cannot be polyfilled";
    }
    function ctor() { }
    ctor.prototype = proto;
    return new ctor();
  };
}

// Define our Base constructor
function Base() {
}

// Define Base#test
Base.prototype.test = function() {
  snippet.log("Base#test");
};

// Derive A from Base
function A() {
  Base.call(this);
}
A.prototype = Object.create(Base.prototype);
A.prototype.constructor = A;

// Define A#test
A.prototype.test = function() {
  snippet.log("A#test");
};

// Derive ChildA from A
function ChildA() {
  A.call(this);
}
ChildA.prototype = Object.create(A.prototype);
ChildA.prototype.constructor = ChildA;

// Define ChildA#test
ChildA.prototype.test = function() {
  snippet.log("ChildA#test");
};

// Run
var b = new Base();
b.test();
var a = new A();
a.test();
var ca = new ChildA();
ca.test();
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

If you're going to be doing a lot of inheritance like this with constructor functions, you might be interested in my helper script Lineage, which makes things more concise and well-contained, and simplifies "supercalls" (chaining to the parent's version of a method). But of course, that script will be outdated soon by ES6's class feature.


text:
Q: MVC4 and dropdown using onchange I've searched several posts on this and the methods all would normally work, however...
I'm in an environment where we use 3 different servers (Dev, UAT and Prod).  All 3 have differing URL structures:
http://dev.com/myusername/applicationname (Dev)
http://uat.com/applicationname (UAT)
http://prod.com/applicationname (Prod)

The issue that I'm having is when I try to use a dropdown I'm having problems getting the url right.  The issue is when I use the following code to populate my dropdown:
 @Html.DropDownList("Owners", ViewData["Owners"] as SelectList, new { onchange = "document.location.href='/Builds/' + this.options[this.selectedIndex].value;" })

It handles the event just fine, but produces a URL of:
http://dev.com/Builds/value.  I need it to be http://dev.com/myusername/application/Builds/value.
Any ideas on how I can accomplish this?

A: Get the base uri then append your stuff to that:
 string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
    Request.ApplicationPath.TrimEnd('/') + "/";

Note that the trim is there because it may or may not end with the trailing slash depending on where it is hosted (root or sub directory)
You might also be able to use
HttpContext.Current.Server.MapPath("~/Builds/")

This might also work:
@HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/Builds/")


text:
Q: Android Dev: PNG Problems? I've tried both using XML and JAVA to create an ImageView in my Android Activity.
Both times, I am able to get all of my other PNG resources I created a day ago to display in the ImageView. The problem is, today I created a new PNG, a crop of one of the working ones, and it will not display through either method.
Is there some guide or reference that I can use to find out why my PNG will not display?
None of the images I create today are working.
XML:
<ImageView
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/speak"/>

Java:
ImageView speak = (ImageView) findViewById(R.id.speak);
speak.setBackgroundResource(R.drawable.logoalt);

I've tried using:
android:src="@drawable/logoalt"

to no avail as well.

A: If you have verified that you can swap out for the images created yesterday and it works, then the problem is indeed the image.  If the old ones don't work, then you changed something in your code or layouts.
Did you create them with a different program or different options?
You could try re-saving the image from a different program, or even the Yahoo smushit service.  I would expect output from that service to be valid.  http://www.smushit.com

A: How did you create your crop? Are you sure it's actually a PNG? It could be a JPEG format or anything else, saved with the extension PNG. That wouldn't work. Try to do it again, and make sure you actually save it as a PNG.


text:
Q: Add-in silently fails to install on Mac Outlook I am developing an add-in for Outlook. My manifest installs without problems in Outlook for the web, but when I try to install the manifest in Outlook for Mac (v16.43), it appears to succeed, but after closing the add-ins window and re-opening it, the add-in has disappeared.
I have generated some logs from Outlook, and see this error:
04/12/2020 14:29:13 Unexpected  Manifest    Issue encountered while parsing manifest,
add-in ID : <id>, Location : Error at element "Action" :
Add-in manifest parsing encountered an unexpected child node, Line=90, CharPosition=16

The relevant parts of the manifest are below. The Action element referred to in the error is the one in the MobileFormFactor section. If I remove the MobileFormFactor section, then the manifest installs successfully.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0" xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0" xsi:type="MailApp">

  ...

  <VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides" xsi:type="VersionOverridesV1_0">
    <VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1" xsi:type="VersionOverridesV1_1">
      <Description resid="residDescription"></Description>
      <Requirements>
        <bt:Sets>
          <bt:Set Name="Mailbox" MinVersion="1.3"/>
        </bt:Sets>
      </Requirements>
      <Hosts>
        <Host xsi:type="MailHost">
          <DesktopFormFactor>
            <ExtensionPoint xsi:type="AppointmentOrganizerCommandSurface">
              <OfficeTab id="TabDefault">
                <Group id="apptComposeGroup">
                  <Label resid="residDescription"/>
                  <Control xsi:type="Button" id="insertMeetingButton">
                    <Label resid="addLabel"/>
                    <Supertip>
                      <Title resid="addLabel"/>
                      <Description resid="residTooltip"/>
                    </Supertip>
                    <Icon>
                      <bt:Image size="16" resid="icon-16"/>
                      <bt:Image size="32" resid="icon-32"/>
                      <bt:Image size="48" resid="icon-48"/>
                      <bt:Image size="64" resid="icon-64"/>
                      <bt:Image size="80" resid="icon-80"/>
                    </Icon>
                    <Action xsi:type="ShowTaskpane">
                      <SourceLocation resid="residTaskpaneUrl"/>
                    </Action>
                  </Control>
                </Group>
              </OfficeTab>
            </ExtensionPoint>
          </DesktopFormFactor>

          <MobileFormFactor>
            <ExtensionPoint xsi:type="MobileOnlineMeetingCommandSurface">
              <Control xsi:type="MobileButton" id="insertMeetingButton">
                <Label resid="prodName"/>
                <Icon>
                  <bt:Image size="25" scale="1" resid="icon-grey16"/>
                  <bt:Image size="25" scale="2" resid="icon-grey16"/>
                  <bt:Image size="25" scale="3" resid="icon-grey16"/>

                  <bt:Image size="32" scale="1" resid="icon-grey32"/>
                  <bt:Image size="32" scale="2" resid="icon-grey32"/>
                  <bt:Image size="32" scale="3" resid="icon-grey32"/>

                  <bt:Image size="48" scale="1" resid="icon-grey48"/>
                  <bt:Image size="48" scale="2" resid="icon-grey48"/>
                  <bt:Image size="48" scale="3" resid="icon-grey48"/>
                </Icon>
                <Action xsi:type="ShowTaskpane">
                  <SourceLocation resid="residTaskpaneUrl"/>
                </Action>
              </Control>
            </ExtensionPoint>
          </MobileFormFactor>
        </Host>
      </Hosts>

    ...

    </VersionOverrides>
  </VersionOverrides>
</OfficeApp>


text:
Q: How to get the data for the last 12 months and split and month-wise in HIVE? Table format for the date column is "yyyyMMdd" and I'm using the following functions to convert into standard format so that HIVE day, months and year can be performed to get the respective values.
(from_unixtime(unix_timestamp(cast(created_day as STRING) ,'yyyyMMdd'), 'yyyy-MM-dd'))

To get the current year data, I would subtract the year obtained from all the records with the year returned by the current date and if it return zero, then it falls in this year.
(year(current_date()) - year(from_unixtime(unix_timestamp(cast(created_day as STRING) ,'yyyyMMdd'), 'yyyy-MM-dd'))) = 0

Problem: If the current date falls in January, I would get only January data month, but i need to get the data from February(last year) to January(current year)?
Also I need to scale this to obtain the last 24 months.

A: I always set my date range parameters outside of Hive and pass them as arguments as this lends itself to reproducibility and testability.
select <fields> from <table> where created_day between ${hiveconf:start_day} and ${hiveconf:end_day}