text:
Q: I want to filter the serial in replace and return if it is used in repair I tried this
$.ajax({
        url: '/api/serials/index/',
        method: 'GET',
        data: {
            reference_no: $(this).val()
        },
        success: function (response) {
            let items_repairs = response[items_repairs];
            let items_replaces = response[items_returns];

            $('#repair_serial_no').empty().append('<option></option>');
            let filteredResponse = response[0].filter(function(item) {
                //Check if the serial is already used in the repair and return table
                let usedInRepair = items_repairs.serial_no.indexOf(item.serial_no) !== -1;
                let usedInReplaces = items_replaces.serial_no.indexOf(item.serial_no) !== -1;
                if(!usedInRepair && !usedInReplaces) {
                    return item;
                }
            });
            filteredResponse.forEach(item => {
                let template = `<option value="${item.id}">${item.serial_no}</option>`;
                $('#return_serial_no').append(template);
            });

but when i click the click the select there is no serial showing
in my /api/serials/index/
public function index(Request $request)
    {
        $serials = SerialNumber::where('reference_no', $request->reference_no)->get(['id', 'serial_no']);
        $items_repairs = ItemsRepair::all();
        $items_returns = ItemsReturn::all();
        $items_replaces = ItemsReplace::all();
        return response()->json([$serials,$items_repairs,$items_returns,$items_replaces]);

A: I think you forgot to set the key as a string.
$.ajax({
...
success: function (response) {
            let items_repairs = response['items_repairs'];
            let items_replaces = response['items_returns'];
...
}


text:
Q: How to install npm in alpine linux So I can't get to install npm in alpine linux. I thought perhaps I can just do a apk add npm but apparently apk search npm returns nothing, even after a apk update. I'm experimenting with all this from the nginx:alpine docker image, i.e. docker run -it nginx:alpine /bin/sh
Edit 1: I can see how the nodejs:alpine dockerfile builds node, but I don't understand how it builds npm
Edit 2: now that I know that npm gets installed with nodejs on alpine, and just for clarification, the reason this wasn't evident to me at first is that on ubuntu 14.04 a sudo apt-get install nodejs would still require a sudo apt-get install npm (which installs development packages e.g. gcc)

A: apk update && apk add nodejs installed the npm binary for me.

A: The issue here is a recent one and is due to changes in Alpine's package repositories between v3.5 and v3.6 or edge.
In v3.5 nodejs included npm
In v3.6 nodesjs does not include npm and the new nodejs-npm package exists.
See here for Alpine packages.
To see what version of packages you are pulling from look at the contents of /etc/apk/repositories

A: I could be wrong, but I think npm is actually a dependency of nodejs.
I've never seen any flavor of package manager install npm alone. Always seems to come packaged with yum install nodejs, or apt-get install nodejs, or apk add --update nodejs.

A: npm comes hand in hand with nodejs.
In the case you cant install node with apk add nodejs, you need fix that first.
Step 1 - do you have the community repo added to your /etc/apk/repositories list? If not, it is very useful to do so. Further details: https://wiki.alpinelinux.org/wiki/Enable_Community_Repository

A: I had an issue with the apk manager.
The package nodejs is no longer installing NPM (see pkgs.alpinelinux.org)
You have to install nodejs-npm
apk add --update nodejs nodejs-npm

A: For the recent versions of Alpine (v3.8+) the correct way to install nodejs with
npm is:
apk add --update nodejs npm
However, npm package depends on nodejs, so you can do:
apk add --update npm
Note: since Alpine 3.8 there is no nodejs-npm package.

A: I have just had to this and can confirm that npm is not a dependency of node.js (at least right now on alpine) and must be installed seperately
i.e apk add --update npm

A: I could successfully install nodejs and npm in alpine Linux with the below commands. Added benefit for this method is we can choose different node version with nvm
apk add -U curl bash ca-certificates openssl ncurses coreutils python2 make gcc g++ libgcc linux-headers grep util-linux binutils findutils

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash

export NVM_DIR="$HOME/.nvm"

[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

nvm install -s <version>

For reference visit here

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to know this code base on ORM or ODM? I want to ask you about this code is ORM base or ODM base?
I use Firebase (NoSQL)
Programming Language is Dart and Flutter.
Future _uploadFile(BuildContext context) async {
final firebaseStorageRef = FirebaseStorage.instance
    .ref()
    .child('post')
    .child('${DateTime.now().millisecondsSinceEpoch}.png');

final task = firebaseStorageRef.putFile(
  _image,
  StorageMetadata(contentType: 'image/png'),
);

final storageTaskSnapshot = await task.onComplete;

final downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();

await Firestore.instance.collection('post').add(
    {
      'contents': textEditingController.text,
      'displayName': widget.user.displayName,
      'email': widget.user.email,
      'photoUrl': downloadUrl,
      'userPhotoUrl': widget.user.photoUrl,
    }
);

A: Since ODM maps between an object model and a document database, and Firebase Storage collects data as a document.
So, it would be considered an ODM base.


text:
Q: Refer to specific element of an XSD model group? Can we create a group and refer to element of that group?
For example, we have a group say
<xs:group name="custGroup">
  <xs:sequence>
    <xs:element name="customerId" type="xs:string"/>
    <xs:element name="customerName" type="xs:string"/>
    <xs:element name="Address1" type="xs:string"/>
    <xs:element name="Address2" type="xs:string"/>
    <xs:element name="mobile" type="xs:string"/>
  </xs:sequence>
</xs:group>

Suppose I want to create another element to have only customerId and mobile:
<xs:element name="custBrief">
  <xs:sequence>
    <xs:element name="customerId" type="xs:string"/>
    <xs:element name="mobile" type="xs:string"/>
  </xs:sequence>
</xs:element>

So, I should be able to refer to custGroup.

A: Option 1: Re-use parts of your group by declaring the constituent elements by reference rather than by name:
<xs:group name="custGroup">
  <xs:sequence>
    <xs:element ref="customerId"/>
    <xs:element ref="customerName"/>
    <xs:element ref="Address1"/>
    <xs:element ref="Address2"/>
    <xs:element ref="mobile"/>
  </xs:sequence>
</xs:group>

<xs:element name="customerId" type="xs:string"/>
<xs:element name="customerName" type="xs:string"/>
<xs:element name="Address1" type="xs:string"/>
<xs:element name="Address2" type="xs:string"/>
<xs:element name="mobile" type="xs:string"/>

This way, your second, similar group can at least share the global declarations of the referenced elements:
<xs:element name="custBrief">
  <xs:sequence>
    <xs:element ref="customerId"/>
    <xs:element ref="mobile"/>
  </xs:sequence>
</xs:element>

Option 2: Use subgroups:
<xs:group name="custGroup">
  <xs:sequence>
    <xs:group ref="custBriefGroup"/>
    <xs:element ref="customerName"/>
    <xs:element ref="Address1"/>
    <xs:element ref="Address2"/>
  </xs:sequence>
</xs:group>

<xs:group name="custBriefGroup">
  <xs:sequence>
    <xs:element name="customerId" type="xs:string"/>
    <xs:element name="mobile" type="xs:string"/>
  </xs:sequence>
</xs:group>

<xs:element name="custBrief">
  <xs:sequence>
    <xs:group ref="custBriefGroup"/>
  </xs:sequence>
</xs:element>

This way, custBriefGroup is defined in one place an re-used.
Note that I took liberties with re-arranging element ordering.
See also: The difference between <all> <sequence> <choice> and <group> in XSD?

A: You're mixing two different schema construction models here.
You can assemble a type from a set of building blocks by using model groups.
You can "subset" a type by using derivation-by-restriction.
But you can't mix the two in the way you are attempting.


text:
Q: Showing only specific test case in test.log I am writing Rails tests using the standard Test::Unit/TestCase.
Is there any way to somehow filter what gets printed to the log, so that you only print the stack for specific test cases.
I have a functional test file with many test cases in it, and I'm really only interested in debugging one test case. Printing my own log statements still requires searching through a few thousand lines of generated log. Or something similar to the RSpec 'pending' functionality.

A: Run from a command line ruby test/unit/my_model.rb to run one test suite. You can also use a debugger, such as (wrapped by) RubyMine or pry, to stop on a specific test case and look at the log.
But if a sledge-hammer does not solve the problem, you can use tweezers: config.logger.level = Logger::WARN in your test.rb, from Set logging levels in Ruby on Rails

A: It is probably better if instead of strangling the output to log/test.log, you become familiar with a command such as grep. Grep allows you to run very advanced search queries through files or directories, as long as your running on some flavor of *nix. The simplest use would be
grep search_term file_name

The reason I say you shouldn't constrict the log output is because someday that could bit you in the **s. Hope this helps.


text:
Q: How to remove specific features of SpatialPolygonsDataFrame based on attributes in R? Since it is not appreciated to ask a question under an already existing question which has been answered, here my question linking to this question URL:Simple way to subset SpatialPolygonsDataFrame (i.e. delete polygons) by attribute in R where you can also acquire the dataset.
Does anyone have an idea how to remove multiple features from the SpatialPolygonsDataFrame based on a vector of values?
head(world.map@data)
#   FIPS ISO2 ISO3 UN                NAME   AREA  POP2005 REGION SUBREGION     LON     LAT
# 0   AC   AG  ATG 28 Antigua and Barbuda     44    83039     19        29 -61.783  17.078
# 1   AG   DZ  DZA 12             Algeria 238174 32854159      2        15   2.632  28.163
# 2   AJ   AZ  AZE 31          Azerbaijan   8260  8352021    142       145  47.395  40.430
# 3   AL   AL  ALB  8             Albania   2740  3153731    150        39  20.068  41.143
# 4   AM   AM  ARM 51             Armenia   2820  3017661    142       145  44.563  40.534
# 5   AO   AO  AGO 24              Angola 124670 16095214      2        17  17.544 -12.296

I would like to remove the features which have the NAMES 'Finland', 'Norway', 'Sweden', 'Denmark' (no offense, I just do not have data for Scandinavia ;) ).
Following approaches failed:
world.map <- world.map[world.map@data$NAME != c('Finland', 'Norway', 'Sweden', 'Denmark'), ]
# does not work at all

world.map <- dplyr::filter(world.map@data, NAMEN %in% c('Finland', 'Norway', 'Sweden', 'Denmark'))
# results in a dataframe, spatial information is lost

I would guess that there is an approach using base::which() and %in%, but I do not have any idea how to go on. The answer of @Jeffrey Evans in this post see URL:https://gis.stackexchange.com/questions/57844/subset-a-spatialpolygonsdataframe-by-id-in-r could provide a useful hint...

A: You may subset the SpatialPolygonsDataFrame by row ids:
# row numbers of countries, exluding scandinavia
ids <- which(
!(world.map$NAME %in% c('Finland', 'Norway', 'Sweden', 'Denmark'))
)

# subset
not_scandinavia <- world.map[ids, ]

# plot
plot(not_scandinavia)


text:
Q: Why is $k[S_{r+1},\ldots,S_n]\to k[X_1,\ldots,X_n]/I$ injective? I'm reading Qing Liu's Algebraic Geometry and Arithmetic Curves.
The proof of the following proposition says that (a) and (b) implies (c). But I can't prove (c) from (a) and (b).

Proposition 1.11.
Let $k$ be a field, and $I$ a proper ideal of $k[X_1,\ldots,X_n]$. Then there exist a polynomial sub-$k$-algebra $k[S_1,\ldots,S_n]$ of $k[X_1,\ldots,X_n]$ and an integer $0\leq r\leq n$ such that:
(a) $k[X_1,\ldots,X_n]$ is finite over $k[S_1,\ldots,S_n]$;
(b) $k[S_1,\ldots,S_n]\cap I = (S_1,\ldots,S_r)$ (this is the zero ideal if $r=0$);
(c) $k[S_{r+1},\ldots,S_n]\to k[X_1,\ldots,X_n]/I$ is finite injective.

So the map in (c) is the canonical map $f:P(S_{r+1},\ldots,S_n)\mapsto \overline{P(S_{r+1},\ldots,S_n)}$ right? Assuming (a) and (b), I proved that $f$ is finite. But I can't prove the injectivity. Here's my attempt for proving the injectivity:
Fix $P,Q\in k[S_{r+1},\ldots,S_n]$ such that $f(P) = f(Q)$. $f(P-Q)=0$ so $P-Q\in I$. By part (b), we have $P-Q\in (S_1,\ldots,S_r)$. Write $P = \sum_{\nu\in\mathbb N^{n-r}} \alpha_\nu S^\nu$ and $Q = \sum_{\nu\in\mathbb N^{n-r}} \beta_\nu S^\nu$. We have $\sum_{\nu\in\mathbb N^{n-r}} (\alpha_\nu-\beta_\nu) S^\nu = P-Q \in (S_1,\ldots,S_r)$. Since $P,Q\in k[S_{r+1},\ldots,S_n]$, all the terms in $P-Q$ doesn't have any of $S_1,\ldots,S_r$. So all $\alpha_\nu-\beta_\nu$ should be $0$ if the following is true:
$\sum_{\nu\in\mathbb N^n}\gamma_\nu S^\nu = 0$ implies that $\gamma_\nu = 0$ for all $\nu\in\mathbb N^n$.
But I don't know if the above statement is true.

A: The ring $k[S_1,\ldots, S_n]$ is exactly the formal linear combinations of terms of the form $\sum_{\nu \in \mathbb{N}^n} \gamma_\nu S^\nu$. So indeed, if a polynomial is zero, then all its coefficients are zero. This is what it means for $k[S_1,\ldots, S_n]$ to be the polynomial ring with generators $\{S_1,\ldots, S_n\}$.


text:
Q: Preserve  while extracting XML text in PHP I have a large XML file that I want to parse and put into a database. For example, this file:
<aa>
    <bb>Some text goes here and
 some more on a new line
    there are other <junk/> tags that I want to keep ignoring
    </bb>
</aa>

My code below uses SimpleXML to parse the text content inside the bb tag, but it silently ignores the
 tag. How can I modify my code to accept
 but not <junk/>?
$xml = simplexml_load_file("ab.xml");
foreach( $xml->bb as $bb ) {
    // $bb now contains the text content of the element, but no tags
}

A: You could strip tags if you know which you want to keep and which you want to remove.
$xml = simplexml_load_file("ab.xml");
foreach( $xml->bb as $bb ) {
    // This will strip everything but

    echo strip_tags($bb,"
");
}

A: I couldn't solve my issue using SimpleXML, but I was successful using DOMElement with a recursive approach. Note that the tag selection criteria is inside the recursive function.
// SimpleXML can be used for the 'simple' cases
$xml = simplexml_load_file("file.xml");
$dom = dom_import_simplexml($xml);
// simpleXML and DOM works with the same underlying data structure, so you can use them interchangably

$aa_content = $xml->aa;
// using simpleXML, $aa is now: "Some text goes here and some more on a new line there are other tags that I want to keep ignoring"
// the <junk> tag is ignore, which is good; but the
 tag is also ignored, which is bad

// the DOM method
foreach( $dom->childNodes as $node ) {
    $textContent = parsePreserveTags($node);
}

function parsePreserveTags($domNode) {
    // we want to preserve tags (for example, html formatting like
)
    $result = '';//$domNode->nodeValue;
    if( $domNode->hasChildNodes() ) {
        foreach( $domNode->childNodes as $node ) {
            // The constant XML_ELEMENT_NODE is defined here http://php.net/manual/en/dom.constants.php
            // If node type is XML_ELEMENT_NODE it's a tag and it can have children.
            // Otherwise, just get the (text) value.
            if( $node->nodeType == XML_ELEMENT_NODE ) {
                // Throw away nodes that match certain criteria
                if( $node->nodeName == 'junk' )
                    continue;

                if( $node->hasChildNodes() ) {
                    // example: "
...
"
                    $result .= '<' . $node->nodeName . '>' . parsePreserveTags($node)
                        . '</' . $node->nodeName . '>';
                } else {
                    // example: "
"
                    $result .= '<' . $node->nodeName . '/>';
                }
            } else {
                // example: plain text node
                $result .= $node->nodeValue;
            }
        }
    }
    return $result;
}

A: As you can exactly say which elements you want to be removed, this is normally done easiest with xpath by querying these elements and then removing them.
In SimpleXML:
$remove = '//junk'; // all <junk> tags anywhere

// simplexml
$sx = simplexml_load_string($xml);
foreach ($sx->xpath($remove) as $element) {
    unset($element->{0});
}

In DOMDocument:
$remove = '//junk'; // all <junk> tags anywhere

// dom
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
foreach ($xpath->query($remove) as $element) {
    $element->parentNode->removeChild($element);
}

Full Example (Demo):
<?php
/**
 * @link http://stackoverflow.com/a/26318711/367456
 * @link https://eval.in/204702
 */

$xml = <<<BUFFER
<aa>
    <bb>Some text goes here and
 some more on a new line
    there are other <junk/> tags that I want to keep ignoring
    </bb>
</aa>
BUFFER;

$remove = '//junk'; // all <junk> tags anywhere

// simplexml
$sx = simplexml_load_string($xml);
foreach ($sx->xpath($remove) as $element) {
    unset($element->{0});
}
$sx->asXML('php://output');

// dom
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
foreach ($xpath->query($remove) as $element) {
    $element->parentNode->removeChild($element);
}
$doc->save('php://output');

Output:
<?xml version="1.0"?>
<aa>
    <bb>Some text goes here and
 some more on a new line
    there are other  tags that I want to keep ignoring
    </bb>
</aa>
<?xml version="1.0"?>
<aa>
    <bb>Some text goes here and
 some more on a new line
    there are other  tags that I want to keep ignoring
    </bb>
</aa>


text:
Q: npm install error: error : spawn ENOENT when trying to build Cordova project I'm having trouble compiling my project, I am beginner with Cordova.
Tried in many ways, to install the dependencies separately (maybe not knife sense), but also tried to change the environment variables (ex: C:\apache-ant-1.9.3 ...).
I also tried to reinstall ("vs-mda and vs-mda-targets").
I am using Visual Studio 2013 Tools for Apache Cordova.

Image with all errors: enter link here

A: We have seen this error prop up when the npm cache is set to %ProgramFiles% which requires admin privileges. If thats the case, set it to a location within %appdata%.
npm config get cache --> find out the current cache location.
npm config set cache %APPDATA%\npm-cache --> set the cache location

You can also have the same issue with npm prefix. To fix that, here are the set of commands
npm config get prefix
npm config set prefix %APPDATA%\npm

A: Unfortunately I have not found a solution to the visual 2013. However encontrie the solution . I changed my machine , and installed visual studio 2015 Which has the Cordova, everything worked Correctly .


text:
Q: How to build LLVM using GCC 4 on Windows? I have been able to build LLVM 2.6 (the llvm-2.6.tar.gz package) using MinGW GCC 3.4.5. I haven't tested properly, but it seems to work.
The trouble is, I have libraries of my own which don't build using GCC3, but which work fine in GCC4 (template issues). I believe the first official GCC4 version for MinGW is GCC 4.4.0.
EDIT
Decluttered - everything useful in the "tried this tried that" info is now in the answer.
EDIT
Most of this question/answer is redundant with LLVM 2.7 - the standard configure, make routine works fine in MinGW with no hacks or workarounds.

A: If at first you don't succeed...
I can now build LLVM 2.6 using MinGW GCC 4.4.0, and it isn't too hard once you know how. I still cannot run the DejaGNU tests, though at first sight that shouldn't be that hard - most likely I'll need the CygWin packages for dejagnu and expect. I also haven't built llvm-gcc yet.
Before the step-by-step, here are the three problems...

Problem 1...

Attempting to build llvm using the standard build instructions fails with the
following compiler error in Signals.cpp (win32/Program.inc)
llvm[1]: Compiling Signals.cpp for Release build
In file included from Signals.cpp:33:
Win32/Signals.inc: In function 'LONG LLVMUnhandledExceptionFilter(_EXCEPTION_POINTERS*)':
Win32/Signals.inc:234: error: exception handling disabled, use -fexceptions to enable

The workaround is to use "make -k -fexceptions" - answer found in the pure language documentation.

Problem 2...

Even with the first workaround, the following compiler error occurs...
ExternalFunctions.cpp: In function 'bool ffiInvoke(void (*)(), llvm::Function*, const std::vector<llvm::GenericValue, std::allocator<llvm::GenericValue> >&, const llvm::TargetData*, llvm::GenericValue&)':
ExternalFunctions.cpp:207: error: 'alloca' was not declared in this scope

It seems that an option is being specified which disables the "alloca" built-in.
The workaround is to edit the problem file
C:\llvm-2.6\lib\ExecutionEngine\Interpreter\ExternalFunctions.cpp

Just after the "#include <string>" line, insert...
#define alloca __builtin_alloca

Problem 3...

Even with the compilation errors fixed, the example programs won't run. The run-time errors are...
Assertion failed: errorcode == 0, file RWMutex.cpp, line 87

This relates to the use of the pthreads library, in the following lines of
RWMutex.cpp
86:   // Initialize the rwlock
87:   errorcode = pthread_rwlock_init(rwlock, &attr);
88:   assert(errorcode == 0);

The basic issue is that pthreads support is included in MinGW GCC, and included in the builds of AFAICT all the GCC4 variants - including the unofficial TDM builds, as well as including MinGW GCC 4.4.0. This was not included with MinGW GCC 3.4.5, which is why LLVM builds fine with default options on that compiler. Using 4.4.0, the LLVM configure script detects the pthreads support and uses it - but the pthreads-w32 library used seems not to be fully compatible.
One workaround is to delete the following files from mingw gcc 4.4.0 as suggested in http://markmail.org/message/d7zw2zjq7svevsci - yes, I know I previously said they weren't there, but I had my folder layout confused...

*

*mingw32\include\pthread.h

*mingw32\include\sched.h

*mingw32\include\semaphore.h

*mingw32\lib\libpthread.a

It is better, though, to simply tell the configure script to disable threads...
./configure --disable-threads

So, the steps are...

First, install the following MinGW and MSYS packages...

binutils-2.20-1-mingw32-bin.tar.gz
mingwrt-3.17-mingw32-dev.tar.gz
mingwrt-3.17-mingw32-dll.tar.gz
w32api-3.14-mingw32-dev.tar.gz
gcc-full-4.4.0-mingw32-bin-2.tar.lzma
make-3.81-20090914-mingw32-bin.tar.gz
tcltk-8.4.1-1.exe
MSYS-1.0.11.exe
msysDTK-1.0.1.exe
bash-3.1.17-2-msys-1.0.11-bin.tar.lzma
bison-2.4.1-1-msys-1.0.11-bin.tar.lzma
flex-2.5.35-1-msys-1.0.11-bin.tar.lzma
libregex-0.12-1-msys-1.0.11-dll-0.tar.lzma

This package list may be more than needed - in particular tcl tk is only needed for the DejaGNU tests, which I haven't got working yet.
Make sure that the \bin folder of your MinGW install is on the PATH (Control Panel, System, Advanced, Environment Variables).
Extract llvm-2.6.tar.gz
Edit the file C:\llvm-2.6\lib\ExecutionEngine\Interpreter\ExternalFunctions.cpp, and just after the line "#include <string>", add the line
#define alloca __builtin_alloca

Start an MSYS command prompt, and run...
cd /c/llvm-2.6
./configure --disable-threads
make -k CXXFLAGS=-fexceptions

I'm assuming you extracted llvm to c:\llvm-2.6
Handy hint - try "./configure --help"
Consider the --enable-targets=host-only and --enable-doxygen configure script options in particular.


text:
Q: Problem starting a RubyonRails application on Media Temple I am having a problem with starting a Ruby On Rails application.
When I type
mtr start <application_name>

It will take a long time and fail with the following message:
Error Executing Command.

But the status of the application will show as "running", only that I will immediately get a HTTP 502 error when trying to access it.
Thanks,

A: The problem was a faulty gem. Doing:
perl ~/check_gems.pl

Identified the culprit and after resintalling it worked fine.


text:
Q: Visual Studio append text to end of lines using find/replace with end line regular expression ($) I am trying to append some text (e.g. "Fish") to the end of every line in a file using Visual Studio or SQL Server Management Studio using the following settings in the find/replace dialog:

*

*Find what: $

*Replace with: Fish

*Use Regular expressions: Checked

This mostly does the job, but for a handful of lines it not only appends "Fish" to the end of the line it also puts it at the beginning of the line. I can't discern any pattern to this behaviour it seems to be almost random, with the larger the file the more lines tending to go wrong.
A similar find/replace with ^ (to put text at the beginning of the line) works with no problem.
Anybody know why this is happening? And also, are there any better suggestions for achieving what I want to?

A: This works in Visual Studio 2012 and 2015:
Find: \r
Replace: Fish\r

Make sure you tick 'Use Regular Expressions' checkbox:

A: I'm not sure why you're seeing that, but you might try something like:
Find: ^.*$
Replace: \0Fish


text:
Q: Unable to install avm I am using instructions from this site to install Anchor on my Windows laptop
https://book.anchor-lang.com/getting_started/installation.html#anchor
I have executed the command avm install latest and it gave this error:
Error: The system cannot find the file specified. (os error 2)
And the next command avm use latest returns this error:
Version 0.25.0 is not installed, no current version. Error: You need to run 'avm install 0.25.0' to install it before using it.
What should I do?

A: Try running the install command like this: cargo install --git https://github.com/project-serum/anchor --tag v0.26.0 anchor-cli --locked
I'm not 100% sure why this works, however, I was running into the same exact problem. If you specify the version via the --tag flag (v0.26.0 would be where you replace with the version you're interested in) and change the command from avm to anchor-cli it seems to work.


text:
Q: Can't change array values in node route I'm trying to set some values based in a conditional so I've decided to make a map in parent array to change some values, but the right values aren't returning for parent array.
app.get('/api/painel/mapa-processos/:idplanejamento/:rotina', (req, res) => {
  let idLista = req.params.idplanejamento
  let rotina = req.params.rotina
  schemas.schemaOps.find({IDPLANEJAMENTO: idLista}).select('NUMEROOP')
  .exec(async (err, result) => {
    let listOps = result.map((result)=>{return result.NUMEROOP})

    const connection = await oracleDB.connect()
    let lastLancamentos = (await connection.execute(queriesOracle.lastLancamentos(listOps))).rows

    lastLancamentos.map(async (row) => {
      let lastAptoMobile = (await connection.execute(queriesOracle.lastAptoMobile(row[0]))).rows

      if (lastAptoMobile.length > 0){
      if (row[2] < lastAptoMobile[0][1]) {
        row[1] = lastAptoMobile[0][0]
        row[2] = lastAptoMobile[0][1]
        row[3] = lastAptoMobile[0][3]
        row[4] = null
        row[5] = lastAptoMobile[0][2]
        row[8] = lastAptoMobile[0][4]
        console.log(row)
      }}
      return row
    })

    connection.close()

    res.json(lastLancamentos)
  })
})


text:
Q: Text messages/website displayed on MAC I'm currently going through a divorce, and I do not want my text messages or browser history showing up on my wife's (used to be our) Mac from my iPhone.  I'm not hiding anything, but since we are no longer together she does not need to know what is going on in my life.  Since I don't have access to the computer, how can I turn off this feature?

A: It sounds like you want to remotely prevent the Mac (which your wife has in her possession) from receiving additional data.
On your iPhone, go to Settings > Messages > Text Message Forwarding, and turn off forwarding for the Mac.
Source: http://www.macworld.com/article/2997176/software-web/how-to-remove-old-devices-from-text-forwarding-on-an-iphone.html
To stop browser history from syncing across devices, also sign the Mac out of your iCloud account. You can do this by signing into https://www.icloud.com/, visiting Settings, and removing the Mac from My Devices.
You may also want to change your iCloud account's password, which you can access via the iCloud account settings (Apple ID > Manage).

A: Go to settings -> iCloud -> turn off anything you don't want synced. As for messages, you must sign out of the current account by going to settings -> iMessage -> tap the Apple ID. Click sign out.


text:
Q: Select Distinct rows with related data I have the following data in a table UserMgr.
ID  |  UserID  |  MgrDbID  |  DeptID
1   |  111     |  2        |  1
2   |  112     |  NULL     |  1
3   |  113     |  5        |  1
4   |  113     |  6        |  2
5   |  114     |  NULL     |  1
6   |  114     |  NULL     |  2
7   |  115     |  5        |  1
8   |  115     |  6        |  2
9   |  116     |  10       |  1
10  |  117     |  NULL     |  1

All the users including the managers are present in the above table. MgrDbID refers to the ID column. There may be multiple records for an user in which case there will
be multiple records for the corresponding manager by DeptID. For Managers, MgrDbID is NULL.
I need the resultset as follows containing distinct UserID and UserID for the corresponding MgrDbID as follows (for users who are not managers). Can anyone please help with the query for the below.
UserID  |  MgrID
111     |  112
113     |  114
115     |  114
116     |  117

A: select u1.userid, min(u2.userid) as MgrID
from UserMgr u1
join UserMgr u2 on u1.UserMgrID = u2.ID
group by u1.userid

A: The above did not return desired result. The following worked for me.
SELECT u1.userID, u2.UserID
FROM users u1 INNER JOIN users u2 ON u1.MgrDbID = u2.ID
GROUP BY u1.userID, u2.UserID


text:
Q: What is $\lim_{n\to\infty} \frac{n}{\sum_{i=1}^n \frac1{a_i}}$ if $a_n=(2^n+3^n)^\frac{1}{n}$? Let $\displaystyle a_n=(2^n+3^n)^\frac{1}{n}$. Compute the limit $$\displaystyle \lim_{n\to\infty}\dfrac{n}{\displaystyle \sum_{i=1}^{n}\dfrac{1}{a_i}}$$
By squeeze theorem, limit of $a_n$ is $3$. Further the sequence $\displaystyle \sum_{i=1}^{n}\dfrac{1}{a_i}$ is strictly monotonic and diverges to infinity since the limit of $n^{th}$ term of the series $\displaystyle \sum_i\dfrac{1}{a_i}$ is not $0$ infact $1/3$. Hence by Cesaro Stolz  theorem for $\cdot/\infty$ case,
$$\displaystyle \lim_{n\to\infty}\dfrac{n}{\displaystyle \sum_{i=1}^{n}\dfrac{1}{a_i}}=3.$$
Is my reasoning correct? Are there more easier ways to solve this?

A: $a_n =  3\Big(1+(\frac23)^n\Big)^{1/n}=3\exp\Big(\frac1n\ln(1+(2/3)^n)\Big)\xrightarrow{n\rightarrow\infty}3$.
The rest follows from Cesaro sums:
$\lim_{n\rightarrow\infty}\frac1n\sum^n_{k=1}\frac{1}{a_k}=\frac{1}{3}$


text:
Q: Pixel-wise colours change in MATLAB I change some the pixel colors ( the pixel who are in the vector row_first) to green,but the image changes this pixel values, but all the image is red,my original image img_crop is double rgb.
My code is below:
 for j=1:size(img_crop,2)%column
       img_crop(row_first(1,j),j,1)=0;
       img_crop(row_first(1,j),j,2)=1;
       img_crop(row_first(1,j),j,3)=0;
 end

Row_first is a vector that has in the first line the rowsindex,  per column for the  pixels in the image_crop that I want toc hange to green.
Basically I want to find the first maximum ( that has the highest row value, and then I want to find the next minimum value before this),and then the minimum that corresponds to my condition ( not important),and then paint the first minimum pixel
This is the code I wrote shown below
for x = 1:size(img_gauss,2)

%   for y=1:size(img_gauss,1)
    % Make a row wise intensity distribution graphic for each column starting
    %from the first row to the last because findpeaks will  assigned the
    %indices in that order, and then select the last
    %max will correspond to the far adventtitia

    %Find the peaks,local maximum for each column and assignment to the
    %respective column

    [z,local_min] = findpeaks(-img_gauss(1:size(img_gauss,1),x));%local min
    % Verify if this local minimum pixels are possible candidates for
    % lumen:
    for w=1:size(local_min,1)%rows
        if (mean_pixel(local_min(w,1),x)<0.0004705 && std_pixel(local_min(w,1),x)<0.0017)
            lumen_local(w,x)=local_min(w,1);

        else
            nao_lumen(w,x)=local_min(w,1);
        end
    end

    % coordinates of the local maximum values
    [g,local_max]=findpeaks(img_gauss(1:size(img_gauss,1),x));%local max

    local_max(:,x)=local_max(:,1);

    % Assignm each maximum and minimum position  to the respective column,
    %per iteration, and sort both in a descendent way
    max_column(1:size(local_max,1),x)=sort(local_max(1:size(local_max,1),x),'descend');
    min_column(1:size(lumen_local,1),x)=sort(lumen_local(1:size(lumen_local,1),x),'descend');

% BW = imregionalmin(img_gauss(y,x));

  end
% end

for q=1:size(img_gauss,2)
    for a=1:size(img_gauss,1)
        if mean_pixel(a,q)<0.0004705 && std_pixel(a,q)<0.0017
            img_gauss(a,q)=1;%white
        else
            img_gauss(a,q)=0;%black
        end
    end
end
figure(9), imshow(img_gauss);
img_close=imclose(img_gauss,ones(20,20));
figure(10),imshow(img_close);

  % The first maximum with the highest row number correspond to the
  % adventícia,so now the first minimum  before correspond to the lumen

  for i=1:size(max_column,2)
      max_adve(:,i)=max_column(1,i);% [row col] of the the first adventicia pixel
      row_first(1,i)= min_column(find(min_column(:,i)<max_adve(:,i),1),i);
  end

   % Put the lumen pixels at green
   for j=1:size(img_crop,2)%column
       img_crop(row_first(1,j),j,1)=0;%R
       img_crop(row_first(1,j),j,2)=1;%G
       img_crop(row_first(1,j),j,3)=0;%B
   end

 figure(11),imshow(img_crop);

Attached I have the original image (left),and the final (right)

Why is this happening, what is the error?

A: You haven't told us how you are defining img_crop.  Nevertheless, by looking at your code, my guess is that you are declaring a RGB image, but you are only setting the first channel to img_gauss.  Declare img_crop this way and try your code again:
img_crop = cat(3,img_gauss,img_gauss,img_gauss);


text:
Q: Nuxt ignores proxy.pathRewrite when `yarn generate` I use inside nuxt.config.js:
  /*
  ** Nuxt.js modules
  */
  modules: [
    '@nuxtjs/axios',
    'cookie-universal-nuxt',
    'nuxt-vue-select'
  ],
  axios: {
    proxy: true,
    credentials: false,
    baseURL: 'https://api.example.com'
  },
  proxy: {
    '/api/': { target: 'https://api.example.com', pathRewrite: {'^/api/': ''} }
  },

unfortunately if I deploy webapp with yarn generate it's using https://example.com/api/... and ignoring pathRewrite rules into https://api.example.com/....
how to solve it?

A: Currently only working workaround for this issue is avoiding using yarn generate and always use yarn build; yarn start on production.
however it's truly disappointing workaround and sometimes even impossible to use (if one hosting doesn't provide explicit support for node webapps).
Has anyone else found a better solution?

A: The problem with yarn generate ist, that it is used for static hosting where you don't have your server side proxy. The only workaround I found was writing your own "pathRewrite"  logic in an axios OnRequest interceptor, so that it behaves similary to the proxy "pathRewrite".
plugin/axios.js
const prod = process.env.NODE_ENV === "production";
const prefix = "/api/";

export default function({ $axios }) {

  $axios.onRequest(config => {

    // The proxy is disabled in prod mode => write own rewritePath here
    if (prod && config.url.startsWith(prefix)) {
      config.url = config.url.replace(prefix, process.env.API_BASEURL);
    }

    return config;
  });
}

nuxt.config.js
 /*
  ** Nuxt.js modules
  */
  env:{
   API_BASEURL:'https://api.example.com'
  },
  plugins:[
    '~/plugins/axios.js'
  ],
  modules: [
    '@nuxtjs/axios',
    "@nuxtjs/proxy",
  ],
  axios: {
    credentials: false,
  },
  proxy: {
    '/api/': { target: 'https://api.example.com', pathRewrite: {'^/api/': ''} }
  },


text:
Q: How to add values to a application.properties file and without overwriting previous values? After packaging a spring boot web application into a jar. Is it possible to load up the properties file and edit it? If not, what would be the best practices to edit properties file while it's packaged in a jar?
Currently I am only able to obtain values from my properties file, but I am stuck on adding new values into it. How can I add @!newServer12 behind @!twtph? I am using "@!" as delimiters.
Properties File sample
ServerName = westpark@!southerndb@!kingsroad@!seamingless@!treehouse@!codebase@!twtph


text:
Q: C# WPF Subscribe to Event in another Class fired from a UserControl I have read through a lot of articles to resolve this problem, but I can't get this to work.
The Situation:
I have a WPF MainWindow where I am loading UserControls into it.
The Mainwindow should listen to an EventHandler in a Class called Navigation. The Event will be fired upon certain changes in the UserControls.
So far I can confirm that the UserControls can fire the Event, but the MainWindow does not pickup the Throw.
Navigation Class:
public class Navigation
{
    public delegate void EventHandler(object sender, EventArgs args);
    public event EventHandler ThrowEvent = delegate { };

    public void NavigationUpdateEvent()
    {
        ThrowEvent(this, new EventArgs());
    }
}

UserControl:
    public delegate void EventHandler(object sender, EventArgs args);
    public event EventHandler ThrowEvent = delegate { };

    Navigation myNavigation = new Navigation();

    public myUserControl()
    {
        InitializeComponent();
    }

    private void CheckBox_Click(object sender, RoutedEventArgs e)
    {
        if (cbCheckBox.IsChecked.Value)
        {
            UMENavigation.NavigationUpdateEvent();
        }
    }

The MainWindow:
    private void DoSomething()
    {
        MessageBox.Show("It worked!");
    }

    private Navigation _Thrower;

    public MainWindow()
    {
        InitializeComponent();

        _Thrower = new Navigation();
        _Thrower.ThrowEvent += (sender, args) => { DoSomething(); };

    }

However, the _Thrower never picks up the Fired Event..
Any help is greatly appreciated! This is starting to hurt :)
Greetings, Tom

A: Navigation instances in UserControl and in the MainWindow are different.
UserControl fires the event for its own instance. At the same time, MainWindow listens for the event from its own instance.
Either use single instance of Navigation, or create a proxy-event in UserControl and subscribe it in MainWindow.
Besides, you don't need to declare your EventHandler. It's already declared.


text:
Q: print the duplicate lines only on fields 1,2 from csv file by the following command we can print the duplicate lines from file
uniq -d string file.txt

but how we can do it on csv file ?
we need to print the duplicate lines only on fields 1,2 from csv file - not include field 3
FS - ","
for example:
 spark2-thrift-sparkconf,spark.history.fs.logDirectory,{{spark_history_dir}}
 spark2-thrift-sparkconf,spark.history.fs.logDirectory,true
 spark2-thrift-sparkconf,spark.history.Log.logDirectory,true
 spark2-thrift-sparkconf,spark.history.DF.logDirectory,true

expected results:
 spark2-thrift-sparkconf,spark.history.fs.logDirectory,{{spark_history_dir}}
 spark2-thrift-sparkconf,spark.history.fs.logDirectory,true

second:
how exclude the duplicate lines from the csv file ( I mean to delete only the duplicate lines on fields 1,2
expected output:
 spark2-thrift-sparkconf,spark.history.Log.logDirectory,true
 spark2-thrift-sparkconf,spark.history.DF.logDirectory,true

A: $ awk -F, 'NR==FNR{a[$1,$2]++; next} a[$1,$2]>1' file.txt file.txt
spark2-thrift-sparkconf,spark.history.fs.logDirectory,{{spark_history_dir}}
spark2-thrift-sparkconf,spark.history.fs.logDirectory,true

Two file processing using same input file twice

*

*NR==FNR{a[$1,$2]++; next} using first two fields as key, save number of occurrences

*a[$1,$2]>1 print only if count is greater than 1 during second pass

For the opposite case, simple matter of changing condition check
$ awk -F, 'NR==FNR{a[$1,$2]++; next} a[$1,$2]==1' file.txt file.txt
spark2-thrift-sparkconf,spark.history.Log.logDirectory,true
spark2-thrift-sparkconf,spark.history.DF.logDirectory,true

A: cut the first two fields, uniq them as you suggested and use the result to grep the lines in the original file:
cut -d, -f1,2 file.cvs |uniq -d|grep -Ff - file.cvs

If the file is not yet sorted, you have to sort it before the uniq:
cut -d, -f1,2 file.cvs |sort|uniq -d|grep -Ff - file.cvs

For the second question (inverted result), use option -u instead of -d:
cut -d, -f1,2 file.cvs |sort|uniq -u|grep -Ff - file.cvs

A: awk solution:
-- to print the duplicate lines only on fields 1,2 from csv file
awk -F, '$1==f1 && $2==f2{ printf "%s,%s,%s\n%s\n", f1,f2,f3,$0 }
        { f1=$1; f2=$2; f3=$3 }' <(sort -t, -k1,1 -k2,2 file.txt)

The output:
spark2-thrift-sparkconf,spark.history.fs.logDirectory,{{spark_history_dir}}
spark2-thrift-sparkconf,spark.history.fs.logDirectory,true

-- exclude the duplicate lines from the csv file (on fields 1,2)
awk -F, 'f1 && f2{ if($1!=f1 || $2!=f2) { printf "%s,%s,%s\n", f1,f2,f3 } else next }
        { f1=$1; f2=$2; f3=$3 }' <(sort -t, -k1,1 -k2,2 file.txt)

The output:
spark2-thrift-sparkconf,spark.history.DF.logDirectory,true
spark2-thrift-sparkconf,spark.history.fs.logDirectory,{{spark_history_dir}}


text:
Q: How to write the same variable x times to file in PowerShell? This is my script right now:
[int]$NumberOfProfiles = Read-Host "Enter the number of profiles You need"
 $WhereToWrite = Read-Host "Enter the full path where You'd like to install the profiles"

$Source = Get-Location
$FolderName = "Fish"
$SourceDirectory = "$Source\$Foldername"

$Variable1 = "Plane"
$Variable2 = "Car"
...
$Variable100 = "Boat"

while ($NumberOfProfiles -gt 0) {
  $DestinationDirectory = Join-Path $WhereToWrite "$Foldername$NumberOfProfiles"
  $PrefsDirectory = "$DestinationDirectory\Data\profile\prefs.js"
$Changer = Get-Variable -Name "Variable$NumberOfProfiles" -ValueOnly
  Copy-Item $SourceDirectory $DestinationDirectory -Recurse -Container
    Write-Host "Made a new profile to" $DestinationDirectory
        (Get-Content $PrefsDirectory) | %{$_.Replace("SomeInfo", "Changer")} | Set-Content $PrefsDirectory
$NumberOfProfiles--
}

The thing I'd like to achieve is that I'd write $Variable1 to the five first copied folders and so on.
E.g. it would look something like that: "Plane" in prefs.js in Fish1, Fish2, Fish3, Fish4, Fish5. "Car" in prefs.js in Fish6, Fish7, Fish8, Fish9, Fish10 and so on.

A: Put the values into an array, and use the array index to choose which one to write.
I have no idea how you've got the folders enumerated, but this will increment the value array index ($ValIdx) once for every 5 folder increments ($i), through 500 folder increments:
$values = ("15","45"..."72")
$ValIdx = 0

for ($i = 1;$i -le 500;$i++)
 {
   '{0} {1}' -f $i,$ValIdx  #Write $Values[$ValIdx] to $folders[$i] here
   $valIdx += -not ($i % 5)
}

Explanation - The modulo operator (%) returns the remainder of a division operation.  ($i % 5) is dividing $i by 5, and returning the remainder.  The -not is evaluating that as a Boolean (true/false) and returning the opposite value.   $ValIdx is an [int], so that Boolean value is being coerced to an [int] for the += operation.
When $i is a multiple of 5, ($i % 5) is zero, which will cast to [bool] as $false.  The -not will flip that to $true. If it's not a multiple of 5, ($i % 5) will return some non-zero value, which will cast to $true, and get flipped to $false.
When the Boolean is cast as [int] for the += operation, it becomes 1 for $true or 0 for $false.  The end result is that every time $i hits a multiple of 5, $ValIdx gets incremented by 1.  If it's not multiple of 5, $ValIdx gets incremented by 0.


text:
Q: Cannot divide by zero error on DB2 Hello all I am using DB2! I have a query that calculates the MPG over a period of 30 days it is done by capturing the change in odometer as the numerator and the sum of fuel purchases as the denominator. However I have a particular unit that is causing me some grief!
Apparently he has not purchased any fuel within the last 30 days and as a result he is causing my query to return an error
Division by zero was attempted. SQLState = 22012

I thought I could be clever and use coalesce but it an unsupported type.
here is the query the mpg!
ROUND(((SELECT MAX(ODOMETER)-MIN(ODOMETER) FROM ODOHIST O
WHERE READINGDATE >= CURRENT DATE - 30 DAYS AND O.UNIT_ID = DEFAULT_PUNIT)/
(SELECT SUM(T2.VOL_PFUEL) FROM FC_POS T2 WHERE T2.DRIVER_ID = DRIVER.DRIVER_ID AND POS_DATE >= CURRENT DATE - 30 DAYS)),2) AS MPG_30DAYS

Rather than actually returning a field of 0 it is just blank, so is there a function similar to coalesce that will force a return value?
Thanks for your help!

A: That would mean that this evaluates to 0:
(SELECT SUM(T2.VOL_PFUEL)
 FROM FC_POS T2
 WHERE T2.DRIVER_ID = DRIVER.DRIVER_ID AND POS_DATE >= CURRENT DATE - 30 DAYS
)

My suggestion is to use NULLIF() in the statement:
(SELECT NULLIF(SUM(T2.VOL_PFUEL), 0)
 FROM FC_POS T2
 WHERE T2.DRIVER_ID = DRIVER.DRIVER_ID AND POS_DATE >= CURRENT DATE - 30 DAYS
)

This will replace the 0 with NULL, which should fix the problem.


text:
Q: Gremlin: select vertex based on comparison of two property values Lets say I have the following Gremlin graph:
g.addV('test1').property('pkey', 100).property('v1', 100).property('v2', 150)
g.addV('test1').property('pkey', 100).property('v1', 100).property('v2', 75)

I want to query for all of the 'test1' labeled vertices where the property value v1 is greater than the property value v2. How do I achieve this in Gremlin?

A: You can use where() step in this fashion:
gremlin> g.addV('test1').property('pkey', 100).property('v1', 100).property('v2', 150)
==>v[0]
gremlin> g.addV('test1').property('pkey', 100).property('v1', 100).property('v2', 75)
==>v[4]
gremlin> g.V().hasLabel('test1').as('a').where('a',gt('a')).by('v1').by('v2')
==>v[4]
gremlin> g.V().hasLabel('test1').as('a').where(gt('a')).by('v1').by('v2')
==>v[4]


text:
Q: Calculate largest power of 2 smaller than n I'm trying to do this operation using bit manipulation in C.
From a number n, substract the largest power of 2 smaller than n.

For example:
6 - 4 = 2
11 - 8 = 3

My approach is:
next2power = nextHighestPowerOf2(n)
previous2power = next2power >> 1;
result = n - previous2power;

I've used following hack from Bit Twiddling Hacks in nextHighestPowerOf2().
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;

The problem with this is next2power overflows  even when I use unsigned long long. n is of the order of 2^64. So this approach isn't working for me.
These two alternate approaches can work here:

*

*By flipping the leading 1 to 0.

*Somehow calculate highest power of 2 smaller than n without overflowing and then subtracting it from n
But I couldn't think of any solution. Does anyone know some other way of achieving this?

A: This should solve your problem
unsigned long long int res = n - 1ULL<<( (int)log2(n-1) );

Of course you must put special conditions when n<=1

A: If you have a 64 bits int. You need to add a v |= v >> 32 to copy into the lower 32 bits.

A: While n is not a power of two, keep turning off the least significat bit set on. You can do the latter operation with n &= (n-1); (think about it).
Expressed in C99:
#include <stdio.h>

int f(int n) {
    while (n & (n-1)) { // n is *not* a power of two
        n &= (n-1);
    }

    return n;
}

int main() {
    for (int n = 1; n < 130; ++n) {
        printf("%d : %d\n", n, f(n));
    }
}

The beauty of this is that the running time is proportional to the number of bits set on.
Sample output:
blazs@blazs:/tmp$ ./x
1 : 1
2 : 2
3 : 2
4 : 4
5 : 4
6 : 4
7 : 4
8 : 8
9 : 8
10 : 8
11 : 8
12 : 8
13 : 8
14 : 8
15 : 8
16 : 16
17 : 16
18 : 16
19 : 16
20 : 16

A: Taking the highest set bit almost always works, and that is easy:
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;  // you need this line for 64bit numbers
v &= ~(v >> 1);

But not always. If n is already a power of two, its highest set bit is equal to itself, not less than. So put that v-- at the beginning back.
FWIW, taking the log and shifting is likely faster, as long as you have a proper built-in way to take an integer log (bsr or equivalent). FP log would likely be a disaster.
ps: none of this was tested.

A: I think you might just be making a mistake when entering, or printing your values; the code in your question works for me:
#include <stdio.h>
int main() {
        unsigned long long input, v;

        input = 7597026128958891522ULL;
        v = input;
        v--;
        v |= v >> 1;
        v |= v >> 2;
        v |= v >> 4;
        v |= v >> 8;
        v |= v >> 16;
        v |= v >> 32;
        v++;
        v= v>>1;
        printf("Input %llu, next lower power of 2 %llu\n", input, v);
}

yielding
Input 7597026128958891522, next lower power of 2 4611686018427387904


text:
Q: Using sed for changing a line of a file containing a path i have a light knowledge of the bash but i search a lot for it and always found my way to do what i want ... except this time ....
My goal is to make a "sed" in a loop so that my script enter a file and replace some lines with others.
for example
1 blabla
2 blabla
3 linetoreplace1
4 blabla
5 blabla
6 linetoreplace2

i must replace line 3 and 6 by something else
The number of each line to replace are stored in a variable :
cat lines
1
14
16
150
159

and the replacement texts (which are links) are stored in another variable :
cat pathlines
./home/newlink_toplace1
./home/newlink_toplace2
./home/newlink_toplace3
./home/newlink_toplace4
./home/newlink_toplace5

so in the end my script "myscript.sh" acting on "file.txt" looks like this :
#!/bin/bash

#the variables containing the number of the lines and the replacing text are already defined in the current directory

#lines.txt
#text.txt

for i in $(seq 1 15)
do

# i put the replacing texte from the list to a variable "reptext"

sed "${i}q;d" text.txt > reptext

#i put the line where we should do the replacement in "line"

sed "${i}q;d" lines.txt > line

# ...and finally the command to do the job

sed -i "${line} s/^\text_to_replace/\'"$reptext"'/" file.txt

done

i received multiple error message including :
 > sed -i -e "${i} s /^\voila/\'"$reptext"'/" file.txt
sed: -e expression #1, char 44: unterminated `s' command

> sed -i "${i}s/.*/'"$reptext"'/" file.txt
sed: -e expression #1, char 13: unknown option to `s'

 > sed -i '${i}s/^\''/\'"$reptext"'/' file.txt
sed: -e expression #1, char 0: unmatched `{'

 > sed -i "${i}s /^\voila/\'"$reptext"'/" file.txt
sed: -e expression #1, char 43: unterminated `s' command

and sometime no error but in the end no action from the script
> sed -i "${i}s/^\voila/\${reptext}/" file.txt

In the end i have tried different sytaxes , stored my variable in a different way , and tried different way to express my variable inside the sed instead of '"$repext"' :
`cat reptext`

echo "$reptext"

"'`("'$£**~##{{[|~|`reptext{~#[`|{[`\\^'"

rm privatepartofmycomputerandlethimsufferslowly
Can you help me
thanks a lot in advance
jan

A: With GNU sed, paste and bash's Process Substitution:
sed -f <(paste -d " " lines.txt pathlines.txt | sed 's/^\([0-9]\+\) \(.*\)/\1s|.*|\2|/') input.txt

With lines.txt:

2
6
12
33
50

Output:

1 blabla
./home/newlink_toplace1
3 linetoreplace1
4 blabla
5 blabla
./home/newlink_toplace2

A: I'd use awk with some other stuff
awk '
    NR == FNR {replacement[$1] = $2; next}
    FNR in replacement {print replacement[FNR]; next}
    {print}
' <(paste lines pathlines) filename.for.replacing

demo
$ awk '
>     NR == FNR {replacement[$1] = $2; next}
>     FNR in replacement {print replacement[FNR]; next}
>     {print}
> ' <(paste lines pathlines) <(seq 20)
./home/newlink_toplace1
2
3
4
5
6
7
8
9
10
11
12
13
./home/newlink_toplace2
15
./home/newlink_toplace3
17
18
19
20


text:
Q: My video couldn't play with MPMoviePlayer?xcode - (void)viewDidLoad
{
    NSString *movieFile1=[[NSBundle mainBundle]pathForResource:@"2" ofType:@"mp4"];
    self.moviePlayer=[[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:movieFile1]];

    [super viewDidLoad];
}

I turned this video to mp4,mov,3gp,m4v ,but always:
Thread 1:signal SIGABRT
Please help me!
I think it should the problem of format .Because when I use the video from support.apple.com
,this code works. So what should I do?

A: do this as [super viewDidLoad]; to the top:
NSString *movieFile1=[[NSBundle mainBundle]pathForResource:@"2" ofType:@"mp4"];
if([[NSFileManager defaultManager] fileExistsAtPath:movieFile1])// check whether file exists
{
  self.moviePlayer=[[MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:movieFile1]];
  if(self.moviePlayer) //reference of movie player created
  {
    [self.moviePlayer prepareToPlay];
    [self.moviePlayer.view setFrame: self.view.bounds];
    [self.view addSubview: player.view];
    [self.moviePlayer play];
  }
}


text:
Q: Multiple prefixes in RestEasy configuration I am using Jboss RestEasy web services, and I need to multiple url to map to that web service. Is there any possibility that I can set multiple prefixes for 'resteasy.servlet.mapping.prefixconfigured
here is my configuration in web.xml
 <servlet-name>REST Service</servlet-name>
      <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servletclass>
      </servlet>

      <servlet-mapping>
        <servlet-name>REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
      </servlet-mapping>

      <servlet-mapping>
        <servlet-name>REST Service</servlet-name>
        <url-pattern>/service/*</url-pattern>
      </servlet-mapping>

      <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
      </context-param>

I want service for both "/rest" and "/service" prefixes

A: For a quick test, I changed your <context-param> into <init-param> inside <servlet> and in RESTeasy 3.0.5 it worked for me.
So a workaround might be to define two servlets with the same configuration and differing only on resteasy.servlet.mapping.prefix value of <init-param>'s, and define two mappings for them.
Beware that now you have two servlets that live their own lives (e.g. separate contexts and lifecycles), which might be unacceptable in some scenarios.
UPDATE: Also take a look at this answer, similar to mine although more elaborated (I haven't tried it myself): https://stackoverflow.com/a/25487574/283519

A: @pwes Thanks a lot!
I was looking to expose two RESTful services.
Say /api1 and /api2 .
Your suggestion works for both what the OP wants and what I wanted too.
Here's how each servelet is configured:
<servlet>
    <servlet-name>entity-manager</servlet-name>
    <servlet-class>
        org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
    </servlet-class>
    <init-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/api1</param-value>
    </init-param>
</servlet>

Second one:
<servlet>
    <servlet-name>entity-manager</servlet-name>
    <servlet-class>
        org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
    </servlet-class>
    <init-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/api2</param-value>
    </init-param>
</servlet>


text:
Q: Memory barriers and Linux kernel spinlock on TILE-Gx In the Linux kernel spinlock implementation for the TILE-Gx architecture, it looks like they don't issue any memory barriers when locking (only when unlocking):
https://github.com/torvalds/linux/blob/master/arch/tile/include/asm/spinlock_64.h
Then I don't understand why instructions cannot be reordered above the locking, which would cause instructions believed by the programmer to be executed while holding the lock, to actually execute before the lock is taken?
Other architectures seem to have at least a compiler barrier:

*

*ARM's spinlock has a memory barrier:
https://github.com/torvalds/linux/blob/master/arch/arm/include/asm/spinlock.h
With comment:

A memory barrier is required after we get a lock, and before we
release it, because V6 CPUs are assumed to have weakly ordered
memory.

*And x86's spinlock has a compiler barrier:
https://github.com/torvalds/linux/blob/master/arch/x86/include/asm/spinlock.h
With comment:

barrier();     /* make sure nothing creeps before the lock is taken */

Why is TILE-Gx different? I thought its memory model was as weak as ARM's memory model. And why don't they even have a compiler barrier?

A: The locking function arch_spin_lock uses arch_spin_lock_slow, which in turn uses cmpxchg.  The implementation of cmpxchg includes a memory barrier instruction (see http://lxr.free-electrons.com/source/arch/tile/include/asm/cmpxchg.h).


text:
Q: Trying to get my CoreData to display in my app I am playing around, learning CoreData and when I got a test application with a UITableView as the root, and it displays the data fine. This would tell me that the database it is pulling the data from is set up correct.
Now I am trying to to have a UIViewController as the initial view controller (via Story board) and it keeps giving me this error -

Cannot create an NSPersistentStoreCoordinator with a nil model

Now I have read a lot of forums and Tutorials and they all basically say that I need to make sure that my xcdatamodel file matches this

URLForResource:@"Model" withExtension:@"momd"]

and it does, again I can display the data if the UITableView is the root view.
Now if I change:
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
    return __managedObjectModel;
}
  NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model"     withExtension:@"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}

into this:
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
    return __managedObjectModel;
}
  //NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model"   withExtension:@"momd"]; // I have commented out this line because the NSURL is no longer being used.
__managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return __managedObjectModel;
 }

The app runs but the TableView is empty, which makes sense to me, as I am not linking to the CoreData file. - The question is- how can I run the app with the setup I have got and show the data?
Cheers Jeff

@response to first answer by Jeff Wolski
Thanks for the answer, I think I am on the right path - I had to alter it slightly to my project to remove the errors. I know have
AppDelegate appDelegate = (AppDelegate) [[UIApplication sharedApplication] delegate];

So I have put this is the
- (NSManagedObjectModel *)managedObjectModel {

Area - is that correct? Also it now has come up with appDelegate variable is not used warning. May be a simple issue, but where do I use that variable now? Cheers Jeff

I have posted what I think is what you are after @Jody Hagins - Hope it helps:-)
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
    return __persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"ViewToNav.sqlite"];

NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                         [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{

    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return __persistentStoreCoordinator;
}

Cheers Jeff

A: You need to set up all of your core data in your app delegate.  The managed object model needs to be a property in your app delegate that your views can access.  In your view controller, you can get a hook to your app delegate with
MyAppDelegate *appDelegate = (MyAppDelegate*) [[UIApplication sharedApplication] delegate];

This will allow you to perform a fetch from whatever view controller you like.
EDIT:
The reason we need to have the appDelegate in the view controller is so that we can access the NSManagedObjectContext that's in the app delegate.  So you don't need to put the NSManagedObjectModel in your view controller.  The NSManagedObjectContext (MOC) gives you access to the entire core data stack that already exists in your app delegate.
In your app delegate, your MOC should be set up as a property.  Now you can do this in your view controller.
myMOC = appDelegate.MOC;

Now myMOC gives you access to your core data.  You will create a NSFetchedResultsController as a property in your view controller.  In your getter method, one of the steps will be to create a NSEntityDescription.  This is where you use your self.myMOC, thus tying your NSFetchedResultsController to your core data model.


text:
Q: Is it possible to search SQLite database that has base64-encoded some text strings? I know you can query a dataBase like so
 NSString *strSelectQuery = [NSString stringWithFormat: @"SELECT * FROM Songs WHERE songname LIKE '%%%@%%'", str];

However, the problem is I encoded the strings (base64) before storing the data into my sqlite database. So regular searches from search bar won't work in this situation. I have another solution that grabs all the Data and stores it in an array then I can predicate it. However, I am wondering if there is a way to search data using the query above somehow even when the strings are encoded by base64.

A: In chat with you, it became clear that the previous developer was having trouble inserting values into the database, so he chose to base64-encode those strings.
Bottom line, searching for substring within base64 string is technically possible, but surprisingly complicated and highly inefficient. I would not advise attempting to doing so.
Instead I would not base64-encode the strings in the database at all. The database will be smaller (base64-encoded string is 33% larger than original payload), the code will be simpler, and searching will now work without any effort at all.

You mentioned that you encountered errors when trying to insert text values into your database. This is because using stringWithFormat to build SQL can cause problems. Consider:
NSString *sql = [NSString stringWithFormat: @"INSERT INTO book (title) VALUES ('%@')", title];
BOOL success = [db executeUpdate:sql];   // FMDB method

But that would fail if the title contained an apostrophe:

Finnegan's Wake

Yes, base64-encoding could get around that problem, but, better, you could just replace that with SQL with ? placeholders, too:
NSString *sql = @"INSERT INTO book (title) VALUES (?)";
BOOL success = [db executeUpdate:sql, title];

By the way, to search, you'd also want to use ? placeholders:
NSString *sql = @"SELECT * FROM book WHERE title LIKE ?";
NSString *searchTerm = [NSString stringWithFormat:@"%%%@%%", searchString];
FMResultSet *rs = [db executeQuery:sql, searchTerm];


text:
Q: Placing image over text How to overlay image on text which is like a pattern image.
like we do in css for applying color with hex value
color: #ffffff;

How it can be done?
I'm trying to get pattern over text

Thanks in advance.

A: I have please check the code..

h1 {

   background: url(http://www.lovethispic.com/uploaded_images/114180-Pink-Glitter-Pattern-.jpg) no-repeat;
   -webkit-background-clip: text;
   -webkit-text-fill-color: transparent;
   font-size:80px
}

Welcome

A: trying this
answer1
=============================================
answer2
demo
html

HAWAII

css
h1, p { margin: 0; }

#container {
    padding: 20px 20px 100px;
    margin: 50px;
    position: relative;
}
#container h1 {
    /* has same bg as #container */
    background: url(http://media.royalcaribbean.com/content/shared_assets/images/destinations/regions/hero/hawaii_01.jpg);

    font-size: 12em;
    font-family: impact;
    left: 0;
    line-height: 100%;
    padding-top: 25px; /* padding + border of div */
    position: absolute; /* position at top left of #containter to sync bg */
    text-align: center;
    top: 0;
    width: 100%;
    text-fill-color: transparent; /* not yet supported */
    background-clip: text; /* not yet supported */
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    -moz-text-fill-color: transparent; /* not yet supported */
    -moz-background-clip: text; /* not yet supported */
    /* text-shadow: 5px 5px 0px rgba(0,0,0,0.1); */
}

================
answer3
css
body {
    font: normal 16px/1.5 Arial, sans-serif;
}

h1, p {
    margin: 0;
    padding: 0 0 .5em;
}

.container {
    margin: 0 auto;
    max-width: 480px;
}

/*
 * Caption component
 */
.caption {
    position: relative;
    overflow: hidden;

    /* Only the -webkit- prefix is required these days */
    -webkit-transform: translateZ(0);
            transform: translateZ(0);
}

.caption::before {
    content: ' ';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: transparent;
    transition: background .35s ease-out;
}

.caption:hover::before {
    background: rgba(0, 0, 0, .5);
}

.caption__media {
    display: block;
    min-width: 100%;
    max-width: 100%;
    height: auto;
}

.caption__overlay {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 10px;
    color: white;

    -webkit-transform: translateY(100%);
            transform: translateY(100%);

    transition: -webkit-transform .35s ease-out;
    transition:         transform .35s ease-out;
}

.caption:hover .caption__overlay {
    -webkit-transform: translateY(0);
            transform: translateY(0);
}

.caption__overlay__title {
    -webkit-transform: translateY( -webkit-calc(-100% - 10px) );
            transform: translateY( calc(-100% - 10px) );

    transition: -webkit-transform .35s ease-out;
    transition:         transform .35s ease-out;
}

.caption:hover .caption__overlay__title {
    -webkit-transform: translateY(0);
            transform: translateY(0);
}

demo


text:
Q: Different formulations of Class Field Theory I was reading up on class field theory, and I have a question. On wiki (http://en.wikipedia.org/wiki/Artin_reciprocity), one formulation is that there's some modulus for which $I^c_K/i(K_{c,1})Nm_{L/K}(I^c_L)$ is isomorphic to $Gal(L/K)$.
Another formulation on the same page is:
$C_K/N_{L/K}(C_L)$ is isomorphic to $Gal(L/K)$.
(where $C_{number\,field}$ is the idele class group of that number field).
How does one relate these two formulations? Is it true that for some modulus, $c$, $I^c_K$ is $C_K$? I don't really see how this fits into one picture.

A: The generalized ideal and (normal) idele class groups (by the generalized ideal class group I really mean ideals prime to $\mathfrak{c}$ for $\mathfrak{c}$ an "admissible cycle," which more or less means divisible by enough primes such that anything congruent to 1 mod it is a local norm) are isomorphic. The short answer for why this is is that given an element in the idele class group, you can get an element of the (generalized) ideal class group since an idele always gives you a fractional ideal. By choosing a suitable representative, you can assume that the ideal you get is actually prime to $\mathfrak{c}$. It is then necessary (and nontrivial) to prove that the corresponding norm groups are mapped to each other, but this is done in Lang's "Algebraic number theory."
There are (at least) two approaches to class field theory:

*

*Define the Artin map globally, on the generalized ideal class group. This has the benefit that you only have to define it on ideals, so just on primes which are unramified (in which case you just use the Frobenius). In this case, it is a lot of work to show that it actually factors not just through the norm group, but also through a group of principal ideals.

*Define the Artin map on ideles by piecing together the local Artin maps.  This then requires some construction of the local Artin maps (which can be done using more-or-less pure group cohomology theory and a little bit of analysis of local fields). One has to check again that it is trivial on principal ideles, which is very nontrivial -- since, again the Artin map was defined by piecing together local things.

So, in a sense, 1 is the one which gives you the ideal form of Artin reciprocity, and 2 gives you the idele one.

A: If you read the initial section or two of the chapter by Tate in Cassels and Frolich, he gives a nice explanation of how to pass from the classical formulation in terms of generalized ideal class groups w.r.t a modulus, and the more modern formulation in terms of idele class groups.  As Tate explains,
the two formulations are indeed equivalent, but it is not quite as simple as saying that $I^c_K = C_K$.   Here is a sketch of the equivalence (of course it is the same is in Akhil Mathew's answer, just slightly more detailed):
Since $I_K^c$ has already been taken to denote the ideals prime to $c$ (at least, this is how I interpret your notation), let me use $J_K$ to denote the ideles for
$K$.  Then we can consider the subgroup $J_K^c$ of the ideles whose entries are all $1$ at any finite place dividing $c$, and at any infinite place.
Then there is a natural surjection $J_K^c \to I_K^c$ given by sending any element
$(a_{\wp})$ of the former to the ideal $\prod_{\wp} \wp^{v_{\wp}(a_{\wp})}$
of the  latter (where the product is over finite places, i.e. prime ideals,
$\wp$).
Now one can show that $K^{\times} J_K^c$ is dense in $J_K$, so
the image of $J_K^c$ is dense in $C_K$.  Since $N_{L/K}(C_L)$ is open in $C_K$,
we see that $J_K^c$ surjects onto $C_K/N_{L/K}(C_L)$.
Now one checks that this map factors through the surjection $J_K^c \to I_K^c$
described in the preceding paragraph, and in fact induces an isomorphism
$I_K^c/i(K_{c,1}) N_{L/K}(I_L^c) \buildrel \sim \over \longrightarrow
C_K/N_{L/K}(C_L)$, as required.
In practice, suppose you want to compute the Artin map on an element of $J_K$:
the algorithm is you first multiply by a principal idele so that the resulting element is in $J_K^c$ times $N_{L/K}(C_L)$.  (You may not know exactly what this
group is, but its not hard to at least identify an open subgroup of it: for example, at any complex infinite place $v$ the norm map is surjective, at any real place $v$ the image of the norm map at least contains the positive reals, and at any finite place $\wp$ the image of the norm map will contain elements which are congruent to $1$ modulo the power of $\wp$ dividing the relevant modulus $c$.)
Now the Artin map on $J_K^c$ factors through the surjection $J_K^c \to I_K^c$,
and is computed on the target using Frobenius elements.
Indeed, this was the argument via which local class field theory was originally proved; one took a local extension, embedded it into a global context (so that the original local situation was realized as $L_{\wp}/K_{\wp}$ for some abelian
extension of number fields $L/K$), and then defined the Artin map via the above computation (which means concretely that one passes from the possibly ramified
situation at $\wp$ to a consideration just at the unramified primes, where everything is easily understood just in terms of ideals and Frobenius elements).
Of course, one then had to check that the resulting local Artin map was well-defined independent of the choice of "global context".
Nowadays, one can define the local Artin maps at all places (unramified or ramified) first.  However, in generalizations to the non-abelian situation (i.e. local and global Langlands) one generally uses the old-fashioned technique of proving certain global results first, and then establishing the precise local results by passing to a well-chosen global context and reducing to a calculation at unramified primes. (This is a bit of an oversimplification, but I think it is correct in spirit.)   So (if one has an eventual aim of understanding modern algebraic number theory and the Langlands program) it is well worth understanding the passage between the idelic and ideal-theoretic view-points on class field theory, and practicing how to use the algorithm described above.


text:
Q: Html Bootstrap4 - three columns I created one container with one row with 3 columns but I dont get 3 columns at all I get only one long column with all content. Any idea why?
I am using Bootstrap 4.
<?php require_once($_SERVER['DOCUMENT_ROOT'].'/core/config.php'); // Define DIR atc ?>
    <!DOCTYPE html>

      <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?php if(isset($title)){ echo $title; }?></title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" />

<?php include(DIR .'includes/ads.php');?>

<?php include(DIR .'includes/article.php');?>

<?php include(DIR .'includes/sidebar.php');?>

A: Well, you used the lgclasses - these are for large monitors. Load it on a large monitor, then you'll see the three next to each other.
If you make the window narrower, they go below each other - that's Bootstrap responsivity;
To get get 3 columns also on smaller screens, use the regular classes, like col-5, col-4 etc. And - and that's the big advantage of Bootstrap - you can also combine several classes for different sizes in the same element, like
, which would result in 2 columns each on a small monitor or 4 columns each on a large monitor.
In this codepen I put your code on top and then copied it once, using the regular col--classes:
https://codepen.io/anon/pen/qxRXPK

A: Add col-sm and col-md css classes to be more specific for different display resolutions


text:
Q: Docker build for numpy , pandas giving error I have a Dockerfile in a directory called docker_test. The structure of docker_test is as follows:
M00618927A:docker_test i854319$ ls
Dockerfile  hello_world.py

My dockerfile looks like below:
  ### Dockerfile

# Created by Baktaawar

# Pulling from base Python image

FROM python:3.6.7-alpine3.6

# author of file
LABEL maintainer="Baktawar"

# Set the working directory of the docker image
WORKDIR /docker_test
COPY . /docker_test

# packages that we need

RUN pip --no-cache-dir install numpy pandas jupyter

EXPOSE 8888

ENTRYPOINT ["python"]

CMD ["hello_world.py"]

I run the command
docker build -t dockerfile .

It starts the building process but then gives the following error in not being able to get the numpy etc installed in the image
Sending build context to Docker daemon  4.096kB
Step 1/8 : FROM python:3.6.7-alpine3.6
 ---> 8f30079779ef
Step 2/8 : LABEL maintainer="Baktawar"
 ---> Running in 7cf081021b1e
Removing intermediate container 7cf081021b1e
 ---> 581cf24fa4e6
Step 3/8 : WORKDIR /docker_test
 ---> Running in 7c58855c4332
Removing intermediate container 7c58855c4332
 ---> dae70a34626b
Step 4/8 : COPY . /docker_test
 ---> 432b174b4869
Step 5/8 : RUN pip --no-cache-dir install numpy pandas jupyter
 ---> Running in 972efa9336ed
Collecting numpy
  Downloading https://files.pythonhosted.org/packages/cf/8d/6345b4f32b37945fedc1e027e83970005fc9c699068d2f566b82826515f2/numpy-1.16.2.zip (5.1MB)
Collecting pandas
  Downloading https://files.pythonhosted.org/packages/81/fd/b1f17f7dc914047cd1df9d6813b944ee446973baafe8106e4458bfb68884/pandas-0.24.1.tar.gz (11.8MB)
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 357, in get_provider
        module = sys.modules[moduleOrReq]
    KeyError: 'numpy'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-8c3o0ycd/pandas/setup.py", line 732, in <module>
        ext_modules=maybe_cythonize(extensions, compiler_directives=directives),
      File "/tmp/pip-install-8c3o0ycd/pandas/setup.py", line 475, in maybe_cythonize
        numpy_incl = pkg_resources.resource_filename('numpy', 'core/include')
      File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1142, in resource_filename
        return get_provider(package_or_requirement).get_resource_filename(
      File "/usr/local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 359, in get_provider
        __import__(moduleOrReq)
    ModuleNotFoundError: No module named 'numpy'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-8c3o0ycd/pandas/
You are using pip version 18.1, however version 19.0.3 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
The command '/bin/sh -c pip --no-cache-dir install numpy pandas jupyter' returned a non-zero code: 1

How can I get this basic setup done?

A: You basically need to install the following on alpine, in order to be able to install numpy:
apk --no-cache add musl-dev linux-headers g++

Try the following Dockerfile:
### Dockerfile
# Created by Baktawar
# Pulling from base Python image

FROM python:3.6.7-alpine3.6

# author of file
LABEL maintainer="Baktawar"

# Set the working directory of the docker image
WORKDIR /app
COPY . /app

# Install native libraries, required for numpy
RUN apk --no-cache add musl-dev linux-headers g++

# Upgrade pip
RUN pip install --upgrade pip

# packages that we need
RUN pip install numpy && \
    pip install pandas && \
    pip install jupyter

EXPOSE 8888

ENTRYPOINT ["python"]

CMD ["hello_world.py"]

You may find this gist interresting:
https://gist.github.com/orenitamar/f29fb15db3b0d13178c1c4dd611adce2
And this package on alpine, is also of interrest I think:
https://pkgs.alpinelinux.org/package/edge/community/x86/py-numpy
Update
In order to tag the image properly, use the syntax:
docker build -f <dockerfile> -t <tagname:tagversion> <buildcontext>

For you, this would be:
docker build -t mypythonimage:0.1 .


text:
Q: Замена текста в кнопке, Modx Revo Не могу изменить текст в кнопке отправки формы, это для ajaxform, вот как записана в коде:

                <button type="submit" class="btn btn-primary" value="Отправить сообщение">[[%af_submit]]</button>

Запись в value не помогает(
Остается постоянно текст - Отправить.

A: Вместо [[%af_submit]] пишите ваш текст, который должен быть в кнопке
<button type="submit" class="btn btn-primary"
        value="Отправить сообщение">Отправить сообщение</button>


text:
Q: Syntax When Combining dd and pv In :
sudo dd if=/dev/sda bs=64k | pv --size 1.5t | dd of=/dev/sdb

Does the block size for dd go on the left side of this after the input as shown or on the right after the output?
With the pipe viewer size option, is it correct that there is no equals sign before the value?  Is it okay to use a decimal value as shown above?

A: A number of issues that might benefit from review.

sudo dd if=/dev/sda bs=64k | pv --size 1.5t | dd of=/dev/sdb

Firstly, you can (vastly) increase the block size and correspondingly increase the throughput. I often use bs=32M. The order of the parameters to dd does not matter, so:
sudo dd if=/dev/sda bs=1M

Next, it doesn't matter whether you specify --size with or without an equals. Long args (those starting with a double dash) usually aren't fussy. However, a quick try out of pv shows that the argument must be an integer. So:
pv --size 1500g

Finally, it would be worth specifying a large (output) buffer for dd, and you'll probably need to run it with root privileges. Because we are using a large buffer it's worth ensuring we have filled it completely before trying to write it out. So you end up with this:
sudo dd of=/dev/sdb bs=1M iflag=fullblock

Putting it all together,
sudo dd if=/dev/sda bs=1M | pv --size 1500g | sudo dd of=/dev/sdb bs=1M iflag=fullblock

I should really point out, though, that on Linux-based systems there's no need to use dd for copying from/to disk drives. On this basis the whole command chain can be simplified to just this,
sudo sh -c 'pv --skip-errors --size 1500g </dev/sda >/dev/sdb'


text:
Q: Laravel VueJs component inline template, unknown custom element I tried to use VueJS inline template component inside Laravel 5.7 but facing this error

[Vue warn]: Unknown custom element:  - did you register
  the component correctly? For recursive components, make sure to
  provide the "name" option

This is my sample code on show.blade.php
@extends('layouts.app')

@section('content')

        <progress-view inline-template>

Test Inline Template Component

        </progress-view>

@endsection

@section('js_after')

@endsection

Default Laravel VueJS instance on app.js
const app = new Vue({
    el: '#app'
});

How can I solve this problem? Do I need to register the component inside Laravel app.js? If yes, what is the syntax that I need?
Thanks

A: When registering a Vue component, you need to include a name, list below:
export default {
        name: 'example-name',
        data() {
            return {
            }
        },

This should help in your situation - let me know :)

A: I finally found the solution to use VueJS inline template in Laravel.
Using this solution, you can enjoy the best of both world, you can use familiar Laravel blade syntax while keep your application reactive using VueJS.
This technique also covered in Laracast episode https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/32
Here is the complete step by step

Step 1: Create a Single File Component. Example ShowUserComponent.vue

Step 2: Reference the file in Laravel app.js and run 'npm run dev' command in terminal

Vue.component('show-user-component', require('./components/admin/users/ShowUserComponent.vue'));

Step 3: Now you can use the component inside Laravel Blade file

@extends('layouts.app')

    @section('content')

            <show-user-component inline-template>

@lang('users.edit')

                            <input type="text" v-model="message">
                            <button @click="store" >Click</button>

                    </show-user-component>

    @endsection

A: I was having the same error as you. In fact I came to your question looking for an answer ♂. Here's what finally worked for me. I'm doing a "subscribe-button" component in Vue, inline.
So I have subscription-button.js (I think there's no problem if you rename it to .vue):
Vue.component('subscribe-button', {
  // logic
})

Then I added this line to app.js just below the require of vue:
window.Vue = require('vue');
require('./components/subscribe-button.js')

In the blade file, I can use now:
<subscribe-button inline-template>
    {{-- blade code here --}}
</subscribe-button>


text:
Q: Validate if age is over 18 years old Just wondering, can I do this to validate that a user has entered a date over 18?
//Validate for users over 18 only
function time($then, $min)
{
    $then = strtotime('March 23, 1988');
    //The age to be over, over +18
    $min = strtotime('+18 years', $then);
    echo $min;
    if (time() < $min) {
        die('Not 18');
    }
}

Just stumbled across this function date_diff:
http://www.php.net/manual/en/function.date-diff.php
Looks, even more promising.

A: I think it is best using the DateTime class for this.

$bday = new DateTime("22-10-1993");
$bday->add(new DateInterval("P18Y")); //adds time interval of 18 years to bday
//compare the added years to the current date
if($bday < new DateTime()){
    echo "over 18";
}else{
    echo "below 18";
}

DateTime::diff can also be used to compare the date with the current date.
$today = new DateTime(date("Y-m-d"));
$bday = new DateTime("22-10-1993");
$interval = $today->diff($bday);
if(intval($interval->y) > 18){
    echo "older than 18";
}else{
    echo "younger than 18";
}

N/B: 1) for the second method , if $bday is greater than $today by 18 years or more, it will return older , so make sure date entered is less than $today
. 2) DateTime works on php 5.2.0 and above

A: Why not? The only problem to me, is the User Interface - how you send out the error message elegantly to the user.
On another note, your function might not work properly as you did not intake a proper birthday (you are using a fixed birthday). You should change 'March 23, 1988' to $then
//Validate for users over 18 only
function validateAge($then, $min)
{
    // $then will first be a string-date
    $then = strtotime($then);
    //The age to be over, over +18
    $min = strtotime('+18 years', $then);
    echo $min;
    if(time() < $min)  {
        die('Not 18');
    }
}

Or you can:
// validate birthday
function validateAge($birthday, $age = 18)
{
    // $birthday can be UNIX_TIMESTAMP or just a string-date.
    if(is_string($birthday)) {
        $birthday = strtotime($birthday);
    }

    // check
    // 31536000 is the number of seconds in a 365 days year.
    if(time() - $birthday < $age * 31536000)  {
        return false;
    }

    return true;
}

A: Here is a simplified extract from what I used for a banking system in Toronto, and this always worked perfectly, taking account of leap years of 366 days.
/* $dob is date of birth in format 1980-02-21 or 21 Feb 1980
 * time() is current server unixtime
 * We convert $dob into unixtime, add 18 years, and check it against server's
 * current time to validate age of under 18
 */

if (time() < strtotime('+18 years', strtotime($dob))) {
   echo 'Client is under 18 years of age.';
   exit;
}

A: if( strtotime("1988/03/23") < (time() - (18 * 60 * 60 * 24 * 365))) {
  print "yes";
} else {
  print "no";
}

...not accounting for leaps years however

A: <?php
 $dob = $_POST['dob'] ?? '';
 $message = '';

 # Validate Date of Birth
 if (empty($dob)){
  # the user's date of birth cannot be a null string
  $message = 'Please submit your date of birth.';
 }
 elseif (!preg_match('~^([0-9]{2})/([0-9]{2})/([0-9]{4})$~', $dob, $parts)){
  # Check the format
  $message = 'The date of birth is not a valid date in the format MM/DD/YYYY';
 }
 elseif (!checkdate($parts[1],$parts[2],$parts[3])){
  $message = 'The date of birth is invalid. Please check that the month is between 1 and 12, and the day is valid for that month.';
 }

 if ($message == '') {
  # Convert date of birth to DateTime object
  $dob =  new DateTime($dob);

  $minInterval = DateInterval::createFromDateString('18 years');
  $maxInterval = DateInterval::createFromDateString('120 years');

  $minDobLimit = ( new DateTime() )->sub($minInterval);
  $maxDobLimit = ( new DateTime() )->sub($maxInterval);

  if ($dob <= $maxDobLimit)
   # Make sure that the user has a reasonable birth year
   $message = 'You must be alive to use this service.';
   # Check whether the user is 18 years old.
  elseif ($dob >= $minDobLimit) {
   $message = 'You must be 18 years of age to use this service.';
  }

  if ($message == '') {
   $today = new DateTime();
   $diff = $today->diff($dob);
   $message = $diff->format('You are %Y years, %m months and %d days old.');
  }
 }
?>
----------------------------------

<?=$message?>

<form method="post" action="">
Your date of birth:

<input type="text" name="dob" id="dob" placeholder="MM/DD/YYYY">

<input type="submit" name="Submit" value="submit">
</form>

A: HTML Input:
 <input type="date" class="form-control" placeholder="Data of Birth" name="dateOfBirth">

PHP code:
function validateDateOfBirth($birthDay)
    {
// convert user input date to string and +18 years;
// compare user input date with current date;

        if (time() < strtotime('+18 years', strtotime($birthDay))) {
            return 'Not 18';
        }
        return "user is older than 18 years old";
    }

A: Php file
if (isset($_POST['bdate'])){
    $bdate = $_POST['bdate'];
    $age = (date("Y-m-d") - $bdate);

}  //if age if 17 or younger error msg
if ($age < 17) {
    echo "Must 18 or older.";
}
else{ //if age is 120 or greather error msg
    if ($age > 120) {
        echo "Real age please.";
    }
    else{
        echo "$age";
    }
}

HTML code:
<form action="" method="POST">

Birth Date   :
    <input id="bdate" type="date" name="bdate" required placeholder="" />

    <input class="btn register" type="submit" name="submit" value="Register" />
</form>


text:
Q: Vue.js - emit to update array not working I have two components: Parent and Child. The Parent has an array of cars the Child is supposed push objects the cars array. My problem is that my Child component turns cars into an object, instead of pushing an object into the cars array. My Parent component:
<template>
   <child v-model="cars"></child>

         {{ car.model }}

</template>

export default {
 data: function() {
  return {
    cars: []
  }
 }
}

My Child component:
<template>

        <button type="button" @click="addCar()">Add Car</button>

</template>

export default {
    methods: {
        addCar() {
            this.$emit("input", { model: "some car model" })
        }
    }
}

Expected results:
cars gets updated and becomes [{ model: "some car model"}, { model: "some car model"}, etc...]
Actual results:
cars becomes an object {model: "some car model"}
Here is my fiddle:
https://jsfiddle.net/t121ufk5/529/
I assume something is wrong with the way i am using v-model on my child component and/or the way I am emitting is incorrect. Can someone help? Thanks in advance!

A: Lets discuss, why you not get proper result.Then we discuss other approach to solve this problem.
Firstly we need to understand how v-model works on custom components by default.
When using a text input (including types such as email, number, etc.) or textarea, v-model="varName" is equivalent to :value="varName" @input="e => varName = e.target.value". This means that the value of the input is set to varName after each update to the input varName is updated to the value of the input. A normal select element will act like this too, though a multiple select will be different.
Now we need to understand,
How Does v-model Work On Components?
Since Vue doesn't know how your component is supposed to work, or if it's trying to act as a replacement for a certain type of input, it treats all components the same with regards to v-model. It actually works the exact same way as it does for text inputs, except that in the event handler, it doesn't expect an event object to be passed to it, rather it expects the value to be passed straight to it. So…
<my-custom-component v-model="myProperty" />
…is the same thing as…
<my-custom-component :value="myProperty" @input="val => myProperty = val" />
So when you apply this approach. You have to receive value as a props. and make sure you $emit name is input.
Now you can ask me at this stage,what you do wrong?
Ok, look at like code @input="val => myProperty = val"
when you $emit whit a new value. this newValue will updated our parent value which you wanna update.
Here is your code this.$emit("input", { model: "some car model" }).
You update your parent value with a object. So your Array updated with a Object.
Lets solve the full problem.
Parent Component:
`
<template>
   <child v-model="cars"></child>

         {{ car.model }}

</template>

export default {
 data: function() {
  return {
    cars: []
  }
 }
}

`
Child Component:
<template>

        <button type="button" @click="addCar()">Add Car</button>

</template>

export default {
    props: ['value']
    methods: {
        addCar() {
            this.$emit("input", this.value.concat({model: "some car model"}))
        }
    }
}

You can actually solved it several way.
Second Approach,
Parent:
<template>
   <child :cars="cars"></child>

         {{ car.model }}

</template>

export default {
 data: function() {
  return {
    cars: []
  }
 }
}

Child:
<template>

        <button type="button" @click="addCar">Add Car</button>

</template>

export default {
    props: {
       cars: {
          type: Array,
          default:[]
       }
    },
    methods: {
        addCar() {
            this.cars.push({ model: "some car model" })
        }
    }
}

Last Approach:
Parent:
    <template>
        <child @update="addCar"></child>

                    {{ car.model }}

    </template>

    export default {
        data() {
            return {
                cars: []
            }
        }
   },
   methods: {
      addCar() {
           this.cars.push({ model: "some car model" })
      }
   }
}

Child:
 <template>

        <button type="button" @click="update">Add Car</button>

    </template>

    export default {
        methods: {
            update() {
                this.$emit('update')
            }
        }
    }

A: It is possible to trigger the event of updating the transmitted value in props
In the parent
<my-component :is-open.sync="isOpen" />

In my-component
this.$emit('update:isOpen', true)


text:
Q: How to get names of resource file in list? Asp.net Mvc application.
In project there is a resource.resx file, where there are information.
From resource file I want to get the list of names.
Everybody can me help?

A: You should be able to do this by iterating through the resources through the  ResourceManager.GetResourceManagerSet() method.
For more info see this question ...

A: try this code
string[] fileEntries = Directory.GetFiles(Application.StartupPath.Replace("bin\\\Debug", "Resources"));
           foreach (string fileName in fileEntries)
               comboBox1.Items.Add(Path.GetFileName(fileName));


text:
Q: Scala Spark: Order changes when writing a DataFrame to a CSV file I have two data frames which I am merging using union. After performing the union, printing the final dataframe using df.show(), shows that the records are in the order as intended (first dataframe records on the top followed by second dataframe records). But when I write this final data frame to the csv file, the records from the first data frame, that I want to be on the top of the csv file are losing their position. The first data frame's records are getting mixed with the second dataframe's records. Any help would be appreciated.
Below is a the code sample:
val intVar = 1

val myList = List(("hello",intVar))

val firstDf = myList.toDF()

val secondDf: DataFrame = testRdd.toDF()

val finalDF = firstDf.union(secondDf)

finalDF.show() // prints the dataframe with firstDf records on the top followed by the secondDf records

val outputfilePath = "/home/out.csv"

finalDF.coalesce(1).write.csv(outputFilePath) //the first Df records are getting mixed with the second Df records.


text:
Q: Element not found error in Selenium Webdriver HTML Code :

    Error: Invalid administrator login attempt.

Selenium Code :
String message =driver.findElement(By.className("messageStackError")).getText();

I am getting the run time error in Selenium webdriver

Unable to locate element: .messageStackError (WARNING: The server did not provide any stacktrace information)
  Command duration or timeout: 19 milliseconds
  For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html

A: Actually this is the timing issue, when you're going to find it would not be present at that time on DOM, so you should try using WebDriverWait to wait until this element could be present as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement el = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("messageStackError")));
el.getText()

Note :- Make sure before finding the element that it is not inside any frame or iframe. If it is inside then you need to switch that frame or iframe before finding element as driver.switchTo().frame("frame id or name");

A: We can also solve this with the help of exception handling and infinite loop:
Here's the code in python -
while 1:
    try:
        driver.find_element_by_class_name("class-name")
        break
    except:
        continue

If there is no exception then the loop will break or else if there's any exception like the element is not found, then the loop will be continued till the element is founded.

A: The element was not loaded in the DOM by the time you requested the text from it.
To delay it you can use
time.sleep(x)
# x is in seconds

in Python,
this will let the element load in the DOM.
For more info you can refer to this
https://selenium-python.readthedocs.io/waits.html