text:
Q: How can i showcase a status of a transfer window which is open in blade file of players panel in a sports management system I m working on a transfer window on a sports management system i have implemented the window and its already open and in the admin panel it shows that the transfer is operating.. i tried in the players panel and i cant get the same status, on, as in admin panel. here it the transfer is closed. below is my code  in my controllers and blades
Here is the PlayersAdminpanel Controller where i have passed all the models associated with the transfer as it it checks the dates if the transfer is still in operation
public function index()
    {
        $teams = Team::get();
        $currentTranfer = TransferWindow::where('start_date', '<=', now())
        ->where('end_date', '>=', now())
        ->first();

        return view('player.index', [
            'teams' => $teams,
            'currentTranfer'=> $currentTranfer,

        ]);

    }

 @if (now() >= $currentTranfer->start_date && now() <= $currentTranfer->end_date)
                                window is open
                            @else
                                window is open
                            @endif

Here is the if statement in blade file in players dashboard which checks is the transfer window is open//


text:
Q: How to create like query in Cassandra? In my keyspace
posts = [
    #key
    'post1': {
        # columns and value
        'url': 'foobar.com/post1',
        'body': 'Currently has client support FOOBAR for the following programming languages..',
    },
    'post2': {
        'url': 'foobar.com/post2',
        'body': 'The table with the following table FOOBAR structure...',
    },
   #  ... ,
}

How to create a like query in Cassandra to get all posts that contains the word 'FOOBAR'?
In SQL is SELECT * FROM POST WHERE BODY LIKE '%FOOBAR%', but in Cassandra?

A: The only way to do this efficiently is to use a full-text search engine like https://github.com/tjake/Solandra (Solr-on-cassandra). Of course you can roll your own using the same techniques manually, but usually this is not called for.
Note that this is true for SQL databases too: they will translate %FOO% to a table scan, unless you use a FTS extension like postgresql's tsearch2.

A: You might create another column family where the keys are the domains, and the values are the keys in your original column family.  That way you could refer to records within a specific domain directly.

A: Cassandra 3.4 added support for LIKE in CSQL. So finally it is available natively.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Indicator species plot (Bubble plot with categorical axes) New to ggplot2/R so id really appreciate someone to shed some light on creating a bubble plot for two categorical axes Species (Y) across different sites North, South, East, West,North.east,Northwest,South.west,South.east (X). The values listed here are indicator values that are relative to sites/species.
Also - how can I determine what value range = size of the bubble? eg. values =0.8-0.9 = largest size..
Sample Data
structure(list(Species = c(13359L, 12867L, 11646L, 13214L, 11413L,
3413L, 13249L, 11374L, 13267L, 2059L, 12941L, 13123L, 1904L,
13252L, 12915L, 12749L, 11577L, 995L), North = c(0.94, 0, 0.9,
0, 0.88, 0.87, 0, 0, 0.86, 0, 0.84, 0.83, 0.83, 0, 0, 0.82, 0.82,
0.81), South = c(0, 0.92, 0.9, 0, 0.88, 0, 0.87, 0.87, 0.86,
0.86, 0.84, 0.83, 0, 0.82, 0, 0.82, 0.82, 0), West = c(0, 0.92,
0.9, 0, 0.88, 0.87, 0.87, 0.87, 0.86, 0.86, 0.84, 0, 0.83, 0.82,
0, 0.82, 0.82, 0), East = c(0, 0.92, 0.9, 0, 0, 0.87, 0.87, 0.87,
0, 0.86, 0.84, 0, 0, 0.82, 0, 0.82, 0.82, 0), North.east = c(0,
0.92, 0.9, 0, 0.88, 0.87, 0.87, 0.87, 0.86, 0.86, 0, 0.83, 0,
0.82, 0, 0, 0.82, 0.81), Northwest = c(0, 0, 0, 0.88, 0, 0.87,
0.87, 0.87, 0, 0.86, 0.84, 0, 0, 0.82, 0, 0, 0, 0), South.west = c(0,
0.92, 0.9, 0.88, 0.88, 0, 0.87, 0, 0.86, 0.86, 0.84, 0.83, 0,
0, 0, 0.82, 0.82, 0), South.east = c(0, 0.92, 0.9, 0, 0.88, 0,
0, 0.87, 0.86, 0, 0.84, 0.83, 0.83, 0, 0, 0.82, 0.82, 0)), class = "data.frame", row.names = c(NA,
-18L))

Thank you !!!

A: Do you mean something like this?
df %>%
    gather(Direction, Value, -Species) %>%
    mutate(
        Species = as.factor(Species),
        Orientation = as.factor(Direction)) %>%
    ggplot(aes(Direction, Species)) +
    geom_point(aes(size = Value))

For setting the range, take a look at scale_size, scale_radius and scale_size_area.


text:
Q: Access Cloudant database from multiple applications I would like to connect to the same database on Cloudant with different applications.  Only one of the applications is going to be writing to the database, and the other would be reading only.
Is this okay to do?

A: Yep! Perfectly OK.
As Kim mentioned, the only thing to worry about with multiple asynchronous connections comes from when different applications / clients try updating the same doc. When this happens, Cloudant will create a conflict, storing both updates so you can sort out which is correct.
Check out Conflict Management in CouchDB for why this occurs and how to deal with it, and the Cloudant docs on conflicts for methods to examine conflicts.


text:
Q: AWS CDK codepipeline action for updating lambda with new build I have a pipeline i'm currently trying to set up via AWS CDK. It's hosted on github and i want to have it update the lambda with a new build every time there's a code update.
Currently, i have this as my stack.
    // the buildspec will be in the repo
    const project = new codebuild.PipelineProject(this, "CahmCodeBuild", {
      buildSpec: codebuild.BuildSpec.fromSourceFilename("buildspec.yml"),
      environment: {
        buildImage: codebuild.LinuxBuildImage.STANDARD_6_0,
      },
    });

    // Create the new pipeline

    const deployPipeline = new pipeline.Pipeline(
      this,
      "LambdaPipeline",
      {
        pipelineName: "lambda-pipeline-name",
        crossAccountKeys: false,
        artifactBucket,
      }
    );

    // define the artifact

    const sourceOutput = new pipeline.Artifact();

    // github connection setup

    const sourceAction = new actions.GitHubSourceAction({
      actionName: "GitHub_Source",
      owner: "my-name",
      repo: "my-repo",
      oauthToken: cdk.SecretValue.secretsManager("my_secret"),
      output: sourceOutput,
      branch: "master", // default: 'master'
    });

    // codebuild setup

    const buildAction = new actions.CodeBuildAction({
      actionName: "CodeBuild",
      project,
      input: sourceOutput,
    });

    // putting everything together!

    deployPipeline.addStage({
      stageName: "Source",
      actions: [sourceAction],
    });

    deployPipeline.addStage({
      stageName: "BuildDeploy",
      actions: [buildAction],
    });

It's at this point i'm actually a little stuck. As far as my experience goes, to update the lambda i just need to upload a new zip of the build. I've checked over the docs and maybe i've just missed it but i cannot find an action that will help me do this.
Is there a function i'm missing? I could manually do it through the codes buildspec.yml using aws-cli but i feel that's just not the right thing to do here.
Edit:
I found this recent(ish) article that went the aws-cli route. Is this still the correct way to do this?


text:
Q: WP Cron job timeout issues I have to run a php function for around 10 minutes. Now I am sheduling the job as a wp-cron-job. But it is getting timed out after 30seconds which is the maximum execution time for php. How to get rid of this timeout issue?

A: In my opinion function that works 10min is not a best idea. Can You maybe refactor Your function or simply try to build batch processing?
My favorite article about that: https://pippinsplugins.com/batch-processing-for-big-data/

A: 30 seconds should be enough for a script in the web, but that's generally speaking.
Running your cron as php-cli will have no timeout limit, you can read more about this here
You can also increase the timeout in any php script, as discussed here - https://stackoverflow.com/questions/3829403/how-to-increase-the-execution-timeout-in-php already.

A: Here is also ready-made class for you to extend and batch process elegantly - https://github.com/gdarko/wp-batch-processing
I used it to run a big batch process on customers, and it's working great.
https://github.com/gdarko/wp-batch-processing
Here is an article about it
https://wptutspro.com/batch-processing-as-background-tasks/


text:
Q: Joint Entropy Performance in Julia I wrote a function to calculate the joint entropy of each column pair in a matrix. But I would like to increase the performance regarding time and memory.
The function looks like this:
function jointentropy(aln)
  mat = Array(Float64,size(aln,2),size(aln,2))

  for i in combinations(1:size(aln,2),2)
    a = i[1]
    b = i[2]
    mina, maxa = extrema(aln[:,a])
    minb, maxb = extrema(aln[:,b])
    h = Array(Float64,(maxa-mina+1,maxb-minb+1))
    h = hist2d([aln[:,a] aln[:,b]],mina-1:1:maxa,minb-1:1:maxb)[3]
    h = h/size(aln[:,1],1)
    I,J,V = findnz(h)
    l = sparse(I,J,log2(V),maxa-mina+1,maxb-minb+1)
    mat[b,a] = - sum(l.*h)
  end
  return mat
end

Matrices that go into this function look like this:
rand(45:122,rand(1:2000),rand(1:2000))

An example with a 500x500 matrix resulted in the following @time output:
elapsed time: 33.692081413 seconds (33938843192 bytes allocated, 36.42% gc time)

...which seems to be a whole lot of memory...
Any suggestions on how to speed up this function and reduce memory allocation?
Thanks in advance for any help!

A: Here are a few ideas to speed up your function.

*

*If the range of all the columns is roughly the same, you can move the extrema computations outside the loop and reuse the same h array.

*hist2d creates a new array: you can use hist2d! to reuse the previous one.

*The assignment h = h/size(aln[:,1],1) creates a new array.

*The division in h = h/size(aln[:,1],1) is done for all the elements of the array, including the zeroes.

*You can use a loop instead of findnz and a sparse matrix (findnz already contains a loop).
.
function jointentropy2(aln)
  n1 = size(aln,1)
  n2 = size(aln,2)
  mat = Array(Float64,n2,n2)

  lower, upper = extrema(aln)
  m = upper-lower+1
  h = Array(Float64,(m,m))
  for a in 1:n2
    for b in (a+1):n2
      Base.hist2d!(h,[aln[:,a] aln[:,b]],lower-1:1:upper,lower-1:1:upper)[3]
      s = 0
      for i in 1:m
        for j in 1:m
          if h[i,j] != 0
            p = h[i,j]  / n1
            s += p * log2(p)
          end
        end
      end
      mat[b,a] = - s
    end
  end
  return mat
end

This is twice as fast as the initial function,
and the memory allocations were divided by 4.
aln = rand(45:122,500,400)

@time x = jointentropy(aln)
# elapsed time: 26.946314168 seconds (21697858752 bytes allocated, 29.97% gc time)

@time y = jointentropy2(aln)
# elapsed time: 13.626282821 seconds (5087119968 bytes allocated, 16.21% gc time)

x - y  # approximately zero (at least below the diagonal --
       # the matrix was not initialized above it)

The next candidate for optimization is hist2d (here, you could use a loop and a sparse matrix).
@profile jointentropy2(aln)
Profile.print()


text:
Q: Run ruby file in rails console I've created a file ebm.rb script to add new entries to a database in rails.
The file is very long, and uses some rails models.
Can I easily execute  ebm.rb in the rails console?
I tried something with load and require, but that didn't work. My ebm.rb file is located in C:\Sites\ebm and my rails project in C:\Sites\rublesql.

A: You can run the code in the file in the context of your rails app with
rails runner

http://guides.rubyonrails.org/command_line.html#rails-runner


text:
Q: Как добавить свою библиотеку в autoload.php? Есть папка с проектом. Внутри нее установлены пакеты в /vendor/ с помощью composer. Внутри /vendor/ есть сгенерированный при установке автозагрузчик autoload.php, который я подключаю на своих страницах.
Вопрос - в какую папку мне лучше складывать свои классы и как организовать их автозагрузку?

A: Обычно свой код кладут в папку src, расположенную в корне проекта на одном уровне вложенности с vendor.
Чтобы подключить автозагрузку в ней необходимо добавить в composer.json
    "autoload": {
        "psr-4": {
            "App\\": "src"
        }
    }

После этого следует выполнить команду composer dump-autoload.


text:
Q: MinGW and XAML/WPF Is it possible to use WPF (and XAML) with MinGW? Is there a tutorial with a sample project somewhere? What libraries do I have to link against and are the WPF headers available in a way that enables using it with MinGW?
(I want to do this for fun; for a real project I'd obviously use VS)
I'd prefer a plain C example (using COM, since I assume this is required), but would also consider a C++ example.

A: I would think not since WPF is a part of the .Net Framework and is used with the CLR whilst MinGW compiles code to native, unmanaged, win32 binaries.  You're not going to be able to 'include' WPF assemblies into a MinGW build.
I think you could possibly use MinGW to compile an unmanaged C++ component (dll) and then use that in a managed (C#) WPF program.


text:
Q: CollectionViewSource in CodeBehind with Template Bindings I'm creating a lookless control based on Selector in WPF with a Dependency Property named ListItems. When SelectedItems is changed, I do:
// CollectionViewSource ListItems = ...
ListItems.Source = newSelectedItems;
ListItems.Refresh();

And in my ControlTemplate I bind it to a ListBox like this:
<ListBox ItemsSource="{TemplateBinding ListItems}"/>

But no items appear in my ListBox.
I have also tried:
<ListBox ItemsSource="{Binding Source={TemplateBinding ListItems}}"/>

What am I missing here?


text:
Q: Failed to transform react-native-reanimated-65-jsc.aar BUILD FAILED in 19s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform react-native-reanimated-65-jsc.aar (project :react-native-reanimated) to match attributes {artifactType=android-aar-metadata}.
      > Execution failed for JetifyTransform: C:\Users\Rahul\Desktop\lcorn\rb\node_modules\react-native-reanimated\android\react-native-reanimated-65-jsc.aar.         > Transform's input file does not exist: C:\Users\Rahul\Desktop\lcorn\rb\node_modules\react-native-reanimated\android\react-native-reanimated-65-jsc.aar. (See https://issuetracker.google.com/issues/158753935)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 19s

    at makeError (C:\Users\Rahul\Desktop\lcorn\rb\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:174:9)
    at C:\Users\Rahul\Desktop\lcorn\rb\node_modules\@react-native-community\cli-platform-android\node_modules\execa\index.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:94:5)
    at async runOnAllDevices (C:\Users\Rahul\Desktop\lcorn\rb\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:106:5)
    at async Command.handleAction (C:\Users\Rahul\Desktop\lcorn\rb\node_modules\@react-native-community\cli\build\index.js:186:9)
info Run CLI with --verbose flag for more details.
PS C:\Users\Rahul\Desktop\lcorn\rb>

"react": "17.0.2",
"react-native": "0.65.0",

A: New upgrade is not yet released react-native-reanimated-65-jsc.aar.
After the installation of the package, navigate to node_modules folder and search for react-native-reanimated. Navigate to android and see if anything ending with 65 is visible.. else it wont work.

Alternate options, [with downgrade to 0.64.2] it does work... but the version gets reset after the build.
This is one of the key file to be updated node_modules> react-native-reanimated > android > build.gradle to make it work
Follow the instructions as given in the site

https://docs.swmansion.com/react-native-reanimated/docs/installation/

set the following too enableHermes: true .. No harm in setting it
Now follow these steps

*

*in your android > gradle > wrapper>gradle-wrapper.properties change
distributionUrl=https://services.gradle.org/distributions/gradle-6.8-all.zip

*android > build. gradle. Change these two items; as class path goes set with 6.8-all goes with 4.2.2

*uninstall react-native .65 and run for 0.64.2

*delete your package-lock.json

*watchman watch-del-all

*Delete node_modules

*run yarn install

*yarn start --reset-cache

*rm -rf /tmp/metro-*

*[This can be an optional step..as RN .64 is set]

Now go back to the node_modules folder and search for the 'react-native-reanimated' folder and change this
artifacts.add("default", file("react-native-reanimated-${minor}.aar"))
to
artifacts.add("default", file("react-native-reanimated-64.aar"))
Now start with your build.. you should not see the issue reported.
. Update

A: Just install react-native-reanimated@2.3.0-alpha.3 or any updated version.
It will fix this issue.

A: I don't think react-native-reanimated supports Hermes on Android with React Native 0.65.0. I was able to fix it removing react-native-reanimated because I don't use it. Maybe you can remove it or disable Hermes.
Installing react-native-reanimated@2.3.0-alpha.2 also fixes it.

A: This issue has been fixed in the latest build (alpha release).
yarn add react-native-reanimated@2.3.0-alpha.3

Here is the list of version releases: https://www.npmjs.com/package/react-native-reanimated?activeTab=versions

A: I have upgraded my react native vers to 0.65.1 and had this problem too. Try to make:

*

*npm uninstall react-native-reanimated

*npm i react-native-reanimated

*cd android

*./gradlew wrapper

*cd ..

*npx react-native run-android

A: If you don't want to use alpha version of the library, you may install react-native-reanimated@2.2.1 too for React Native 0.65


text:
Q: Django model clean and ManytoMany problem I want to check my Foo instance if it belongs to a category yet my category is a many to many attribute thus I get "'Foo' instance needs to have a primary key value before a many-to-many relationship can be used." once I try such:
class Category(models.Model):
    name = models.CharField(max_length=120)

class Movie (models.Model):
    poster = models.ImageField(blank=True)
    categories = models.ManyToManyField(Category)

    def clean(self):
            try:
                self.categories.all().get(db_name="special")
                self.poster.url = u'/media/special_img.png'
            except Category.DoesNotExist:
                pass

A: You can't check if Foo belongs to a category yet until you save it. But since it isn't saved anyway, you can be sure that it doesn't belong to a category yet.
One way to check wheter it has been saved already is by using if foo.pk. The pk is the primary key and it will be None if it hasn't been saved yet.


text:
Q: node command while defining a coordinate in TikZ This question is related to Strange behavior in TikZ \draw command but is not the same.
While working with coordinates and nodes in TikZ, I was expecting that:
  \coordinate (x) at (4,0) node[right] {$x$};
  \coordinate (y) at (0,3) node[above] {$y$};

and
  \node[right] at (x) {$x$};
  \node[above] at (y) {$y$};

would yield the same result. But they don't. I get the following output:

With \coordinate (x) at (4,0) node[right] {$x$};, I meant, the system will create a node at (4,0) and will place the text $x$ to its right.
Based on the output, I see the text $x$ is placed at (0,0), with the above command.
Why does this happen.
MWE:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{intersections}
\begin{document}
\begin{tikzpicture}
  \coordinate (x) at (4,0) node[right] {$x$};
  \coordinate (y) at (0,3) node[above] {$y$};

  \node[right] at (x) {$x$};
  \node[above] at (y) {$y$};

  \draw[<->,thick] (0,3) |- (4,0);
\end{tikzpicture}
\end{document}

A: It doesn't give you the expected result because the syntax is not appropriate. (At which level do you expect an explanation? Does it help that in \coordinate (x) at (4,0) node[right] {$x$}; at (4,0) got "absorbed" by coordinate (x) so that TikZ adds the default coordinate (0,0) to interpret node[right] {$x$}?) You can condense all statements to one line.
\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}
  \draw[<->,thick] (0,3) coordinate (y) node[above] {$y$} |- (4,0) coordinate (x)  node[right] {$x$};
\end{tikzpicture}
\end{document}

A: In section 17.2.1 of the TikZ manual, the commands for such works are shown:

*

*\path ... node ... (1.1)
or \node ... (1.2)

*\path ... coordinate ... (2.1)
or \coordinate ... (2.2)

\coordinate ... node ... are not present for the same job! In fact, since \coordinate is the same as \path coordinate so \coordinate (x) at (4,0) node[right] {$x$}; is understood as
\path coordinate (x) at (4,0);  % or `\coordinate (x) at (4,0);
\path node[right] {$x$}; % (0,0) in case no coordinates are specified

This makes the outputs of \coordinate (x) at (4,0) node[right] {$x$}; and \node[right] at (x) {$x$}; not the same at all.
That is why we get

with this code
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\coordinate (x) at (2,0) node[draw,right] {world};
\fill (x) circle (1pt)
    (0,0) circle (1pt);
\end{tikzpicture}
\end{document}

and we get

with this code
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\node[draw] (x) at (2,0) {Hello} node[draw,right] {world};
\fill (0,0) circle (1pt);
\end{tikzpicture}
\end{document}

So how to solve it? We can't combine (2.2) or (1.2) with ... node ..., but we can do it with (1.1) or (2.1):
\path (4,0) coordinate (x) node[right] {$x$};

Remember that \draw, \fill, \filldraw... are all daughters of \path, so they are all valid. But \node and \coordinate are not – they are less general versions of \path..

I found this using the draw powerful trick :)

A: try the following:
\documentclass{article}
\usepackage{tikz}
%\usetikzlibrary{intersections} not used in this mwe

\begin{document}
\begin{tikzpicture}
  \coordinate[label=right:$x$] (x) at (4,0);
  \coordinate[label=above:$y$] (y) at (0,3);

  \draw[<->,thick] (y) |- (x);
\end{tikzpicture}
\end{document}

addendum:
as response to Martin Argerami coments below my answer, who is convinced that my answer not address op problem (and consequently he apparently down vote it, for what i'm very grateful. his message is very clear: don't show people some possible solution for which they not explicit ask). however let me note some my view on the problem:

*

*in answer i only suggest to see if my suggestion can help to op

*it solve the problem of placement of coordinate labels (in this is all about it, isn't it?)

*if the answer is not helpful, op can select one from other two answers as the best one and accept it.

*to be strict to Martins' consideration, that he should down vote many other answers, which try show another possibility to achieve op goal (nice picture, table, etc) or is written as exercise (personal or for op) ...

*on the end, i'm still convinced, that my answer not harm anyone, it only show another way how to draw coordinates shown in op mwe. is this worth for down voting it?


text:
Q: How to get a list with all branches and the latest tag that includes a number in Git? I have many Git branches containing different version tags. I am looking for a solution, where I get a list of all my branches and their latest numbered tag line by line. (Versioning has always the same format: X.Y.Z)
Example:
master  : 2.2.2
branchB : 2.2.1
branchC : 2.0.0

A: Maybe it is exactly what you want -
git branch -a | while read branch; do
    echo "$branch"; git describe --tags --abbrev=0 $branch
done

It shows all local & remote branches with latest tag.
Sample Output:
* master
0.3
branch-1
0.2.1
remotes/origin/master
0.3

A: If you don't have any unwanted tags littering up the place @sajibkhan's got the right idea,
git for-each-ref refs/heads refs/remotes --format='
        printf '%s: ' %(refname:short); git describe --tags --abbrev=0 %(refname:short)
' |sh

or with a more familiar while read,
git branch -a|sed s/.//|while read branch; do
        printf '%s: ' "$branch"; git describe --tags --abbrev=0 $branch
done

but your

their latest numbered tag

makes me think you've got some tags that aren't numbered, and those would make the git describe give wrong results sometimes.

git describe has a --match option, so if you can cook up a positive-match glob for the tags you want to consider, e.g. if --match=[0-9]* will do it, just add that.  But e.g. linux has tags like v4.8.1 and v2.6.3-rc7, and matching just the first with a glob pattern ain't easy.
For situations like that, there's a really good technique for ref surgery:
scratch=`mktemp -d`
git clone -s --mirror . "$scratch"
cd !$

makes a really quick scratch clone with duplicated refs but no actual content. The -s is short for --shared, the repo uses the main object db, and mirrored clones are always bare so there's no checkout.  Use shared-object clones for any temporary work where you're really unsure you'll want the results, or you want before-and-afters.
So now that you're in your sandboxed mirror, you can just delete the refs you don't want to see here:
git for-each-ref refs/tags/*[^0-9.]* --format='
        delete %(refname)
' | git update-ref --stdin

deletes every tag that has a non-digit-or-dot in its name anywhere.
And the cleaned-up scratch-monkey refname space is ready for the straightforward git describes above.

This is a general technique: you can push and fetch any refs you want, anywhere with a url or pathname, with any kind of rewriting you want.  This includes your local repo.  Here, for instance, is the brutal way to make or fast-forward local branches for every remote-tracking branch:
git fetch . refs/remotes/origin/*:refs/heads/*

(do that in a scratch clone first...)


text:
Q: Single query in location tracking system I have this system that keeps track of the location of items.
Example tables:
constb
consid cons
  1    Nint
  2    PS
  3    XB
  4    AT

consloctb
locid  consid  loc
  1       1     GS
  2       2     IT
  3       2     GG
  4       1     IG
  5       2     SS
  6       3     SM
  7       3     FB
  8       1     SS
  9       2     SM
  10      3     IT
  11      4     SM

And the result would show the current location of all the items. It would look like this:
Nint - SS
PS - SM
XB - IT

The logic I'm thinking right now is to do a nested loop.
$res=mysqli_query($con,"SELECT * FROM constb ORDER BY id");

while($row=mysqli_fetch_array($res)){

  $consid=$row["consid"];

  $res2=mysqli_query($con,"SELECT * FROM consloctb WHERE consid='$consid' ORDER BY locid DESC LIMIT 1");

  while($row2=mysqli_fetch_array($res2)){

    echo $row["cons"]." - ".$row2["loc"];

  } /* END OF SECOND LOOP */

} /* END OF FIRST LOOP */

This would show the results that I wanted.
And if I add a search function, I would do the same nested loop process, just gonna add another WHERE condition in the second loop, if the searched location is the same with the loc column.
$srchloc=$_POST["search"]; /* DATA SUBMITTED */

$res=mysqli_query($con,"SELECT * FROM constb ORDER BY id");

while($row=mysqli_fetch_array($res)){

  $consid=$row["consid"];

  $res2=mysqli_query($con,"SELECT * FROM consloctb WHERE consid='$consid' AND loc='$srchloc' ORDER BY locid DESC LIMIT 1");

  while($row2=mysqli_fetch_array($res2)){

    echo $row["cons"]." - ".$row2["loc"];

  } /* END OF SECOND LOOP */

} /* END OF FIRST LOOP */

Example search, if a user search for items that is currently in the SM, the result would show
PS - SM
AT - SM

Doing the second option I think might slow the search process. How can I achieve this using a single query? Or making the process faster?

A: If you want to list the current location of all the items:
SELECT t.cons,
       t.loc
FROM
  (SELECT constb.consid AS id,
          constb.cons AS cons,
          consloctb.loc AS loc
   FROM constb
   LEFT JOIN consloctb ON constb.consid = consloctb.consid
   ORDER BY constb.consid,
            consloctb.locid DESC) AS t
GROUP BY t.id;

If you want the result filtered for a searched location, you can add the HAVING clause:
SELECT t.cons,
       t.loc
FROM
  (SELECT constb.consid AS id,
          constb.cons AS cons,
          consloctb.loc AS loc
   FROM constb
   LEFT JOIN consloctb ON constb.consid = consloctb.consid
   ORDER BY constb.consid,
            consloctb.locid DESC) AS t
GROUP BY t.id HAVING t.loc='SM';


text:
Q: JAVA/JNI - Load native DLL with circular dependency I try to load C++ code in my Java project with JNI. I have many several DLL to load, and unfortunately there is a cyclic dependency between two of them: dll A needs dll B which in turn needs dll A!
I know it is a bad programming design to have circular dependencies between DLL, but in my project the C++ code is a black box to me.
Is there any way to load DLL with a cyclic dependency?
My code is quite simple:
System.loadLibrary("myDLLA"); // needs dll B to be loaded!
System.loadLibrary("myDLLB"); // needs dll A to be loaded!
System.loadLibrary("myDLLC"); // needs dll B
// then call my native method implemented in dll C

The Java library path is OK and contains the two DLL (it is given as VM argument, I dumped it and checked it at run time too).
The cyclic dependency was confirmed by Dependency Walker.
The error is :
java.lang.UnsatisfiedLinkError: E:\...\myDLLA.dll: Can't find dependent libraries
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1928)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1854)
at java.lang.Runtime.loadLibrary0(Runtime.java:845)
at java.lang.System.loadLibrary(System.java:1084)

My project is developed in Eclipse (Helios) as a dynamic web project deployed on a tomcat 6 server.

A: On Windows, the DLL loader will follow the PATH to resolve external references. You can add the directory of myDLLB.dll to PATH globally (through System properties-> advanced), or on command line which launches your Java app (set or xset), or from your Java code.


text:
Q: mysql connector in a separate python process, cannot pickle in constructor / __init__ I want to put some SQL db processing (when some items are received a batch is written) in a separate process in python (currently I have a main thread that spawns another callback handle thread to process data that is received from the internet by yet another reader thread - IB TWS API for the ones interested)
class sqlExecutor(multiprocessing.Process):

  conn = None
  cursor = None

  def __init__(self, task_queue):
    multiprocessing.Process.__init__(self)
    self.task_queue = task_queue

    self.conn = mysql.connector.connect(
      host="192.168.10.10",
      user="homestead",
      password="secret",
      database="xxxxx"
    )

    self.cursor = self.conn.cursor()

  def run(self):
    batch = []
    while True:
      row = self.task_queue.get()
      if row is None:
        self.task_queue.task_done()
        break
      # task complete for join function
      self.task_queue.task_done()
      if len(batch) == 4:
        # write to db
        insert_sql_query = """
        INSERT IGNORE INTO tickvalues (contractid, dttm, value, tickType)
        VALUES ( %s, %s, %s, %s )
        """
        self.cursor.executemany(insert_sql_query, batch)
        self.conn.commit()
        batch.clear()

      batch.append(row)

  def __del__(self):
      self.cursor.close()
      self.conn.close()

The app.run() (which derives from EWrapper, EClient) contains:
    ...
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    conId = self.contractList[reqId].conId

    # send tuple to the other process
    item = (conId, now, price, tickType)
    self.tasks.put(item)
    ...

Part of run() that is part of the data processing thread and is started from main thread, e.g.,
  thread_app = threading.Thread(target=app.run)
  thread_app.start()

This is the main thread:
def main():
  app = BasicApp()
  app.connect("127.0.0.1", 7497, 0)

  tasks = multiprocessing.JoinableQueue()

  sqlTickSaver = sqlExecutor(tasks)

  sqlTickSaver.start()

  app.tasks = tasks
  ...

When running it gives me 'TypeError: cannot pickle 'SSLSocket' object'. But I read some suggestions elsewhere that I should put the mysql connector completely in the process itself/constructor (which I did as far as I know). Besides, I send only tuples via the queue (and according Python's documentation I should be able to pickle/serialize that type).
What would be a solution? When leaving out the mysql things in init that error dissappears (but something else goes wrong so I guess it has something to with mysql connector).


text:
Q: How to parse text into json in express sever using bodyParser? I have an express server which is acting as an API, main.ts (this has the code to up the server) looks somewhat like this
const app = express();

app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.text({ type: "text/plain" }));
app.use('/', routes);

app.listen(8080, () => {});

and the routes object has a GET definition as :-
routes.get('/myObject', (request: Request, response: Response) => {
    console.log(request.body); // Output : {}
});

I have another server from where I send a request but the request body is not getting parsed as it should
The XHR I'm sending from the second server is :-
    const request: XMLHttpRequest = new XMLHttpRequest();
    request.open("GET", "http://localhost:8080/myObject");
    request.setRequestHeader('Accept', 'application/json');
    request.setRequestHeader("Content-Type", "text/plain");
    request.setRequestHeader('Access-Control-Allow-Origin', '*');
    request.onload = () => {
        console.log(request.status);
    };
    request.onerror = (err) => {
        console.log(request.status);
    }
    request.send(JSON.stringify({ "key": "value" }));

But on my express server, { "key": "value" } is not appearing only {} is coming?
Any idea what is wrong here?
Also if I do get "{\"key\":\"value\"}" in the express server can I implicitly convert it to a JSON object which can be sent as request.body?

A: Change the method to POST  instead of GET and give it a try.
Responses for GET´s have their body set to null.


text:
Q: Styling Scrollbars on QTextEdit (Using custom images) I have the simple UI below and I want to make customize everything in it. I've managed to use custom Window using a transparent PNG and I also tried making custom buttons with different states and they all work perfectly. Does anyone know how to style the scrollbars on QTextEdit?
I searched around everywhere and I couldn't find anything about QTextEdit scrollbars.
#!usr/bin/env python
#-*- coding: utf-8 -*-

import sys
import os.path #file check
from PyQt5 import QtWidgets, QtCore, QtGui #pyqt stuff
from PyQt5.QtCore import QPoint #dragable window
from gui.guiMain import Ui_main

class mainUi(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        self.ver = '2.0.0'
        QtWidgets.QMainWindow.__init__(self, None)
        self.setAcceptDrops(True) #accept file drops
        self.ui = Ui_main()
        self.ui.setupUi(self)
        self.oldPos = None
        self.setFixedSize(401, 286) #no resize
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #frameless window
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setAttribute(QtCore.Qt.WA_NoSystemBackground)
        self.setStyleSheet("background:transparent;")
        self.ui.exitBtn.setStyleSheet("""
                QPushButton {
                    qproperty-iconSize: 32px 32px;
                    image: url(":/res/icons/close.png");
                }
                QPushButton:hover {
                    image: url(":/res/icons/close-hover.png");
                }
                QPushButton:pressed {
                    image: url(":/res/icons/close-focus.png");
                }
            """)
        self.ui.btnBtn.setStyleSheet("""
                QPushButton {
                    qproperty-iconSize: 32px 32px;
                    image: url(":/res/icons/main.png");
                }
                QPushButton:hover {
                    image: url(":/res/icons/main-hover.png");
                }
                QPushButton:pressed {
                    image: url(":/res/icons/main-focus.png");
                }
            """)
        #ui functions
        self.ui.exitBtn.clicked.connect(self._exit)
        self.ui.btnBtn.clicked.connect(self._btnBtn)

        ##########################
        ####### Variables ########
        ##########################
        title = 'Test Window'
        self.setWindowTitle(title)
        self.ui.titleLbl.setText(title)
        self.ui.titleLbl.setStyleSheet('QLabel {color: white; font-size:35px; font-family:IranNastaliq;}')
        text = '
'
        sher = """12345
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text..."""
        sher = sher.replace('\n', '
')
        text += sher
        text += '
'
        self.ui.textEdit.setText(text)
        self.ui.textEdit.setStyleSheet("""
            QTextEdit {
                font-size:15px;
                font-family:Vazir FD;
            }
        """)

    ##############################
    ####### Functions ############
    ##############################
    def mousePressEvent(self, event):
        self.oldPos = event.globalPos()

    def mouseMoveEvent(self, event):
        if self.oldPos:
            delta = QPoint (event.globalPos() - self.oldPos)
            #print(delta)
            self.move(self.x() + delta.x(), self.y() + delta.y())
            self.oldPos = event.globalPos()

    def _btnBtn(self):
        print('btnBtn')

    def _exit(self):
        self.close()

    def closeEvent(self, event):
        self.close()

def main():
    app = QtWidgets.QApplication(sys.argv)
    QtGui.QFontDatabase.addApplicationFont(':/res/fonts/Vazir-FD.ttf') #add custom font no install
    QtGui.QFontDatabase.addApplicationFont(':/res/fonts/IranNastaliq.ttf') #add custom font no install
    main = mainUi()
    main.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

A: To do this, you have to add a scrollbar first then attach it to your QTextEdit using setVerticalScrollBar. Then you can customize the QScrollBar itself. Here is an example. In my UI file, I've added a scrollbar called sbar which gets attached to the textEdit:
#!usr/bin/env python
#-*- coding: utf-8 -*-

import sys
import os.path #file check
from PyQt5 import QtWidgets, QtCore, QtGui #pyqt stuff
from PyQt5.QtCore import QPoint #dragable window
from gui.guiMain import Ui_main

class mainUi(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        self.ver = '2.0.0'
        QtWidgets.QMainWindow.__init__(self, None)
        self.setAcceptDrops(True) #accept file drops
        self.ui = Ui_main()
        self.ui.setupUi(self)
        self.oldPos = None
        self.setFixedSize(401, 286) #no resize
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint) #frameless window
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.setAttribute(QtCore.Qt.WA_NoSystemBackground)
        self.setStyleSheet("background:transparent;")
        self.ui.exitBtn.setStyleSheet("""
                QPushButton {
                    qproperty-iconSize: 32px 32px;
                    image: url(":/res/icons/close.png");
                }
                QPushButton:hover {
                    image: url(":/res/icons/close-hover.png");
                }
                QPushButton:pressed {
                    image: url(":/res/icons/close-focus.png");
                }
            """)
        self.ui.btnBtn.setStyleSheet("""
                QPushButton {
                    qproperty-iconSize: 32px 32px;
                    image: url(":/res/icons/main.png");
                }
                QPushButton:hover {
                    image: url(":/res/icons/main-hover.png");
                }
                QPushButton:pressed {
                    image: url(":/res/icons/main-focus.png");
                }
            """)
        #ui functions
        self.ui.exitBtn.clicked.connect(self._exit)
        self.ui.btnBtn.clicked.connect(self._btnBtn)

        ##########################
        ####### Variables ########
        ##########################
        title = 'Test Window'
        self.setWindowTitle(title)
        self.ui.titleLbl.setText(title)
        self.ui.titleLbl.setStyleSheet('QLabel {color: white; font-size:35px; font-family:IranNastaliq;}')
        self.ui.sbar.setStyleSheet("""
QScrollBar:vertical {
    border: 1px solid #999999;
    background:white;
    width:10px;
    margin: 0px 0px 0px 0px;
}
QScrollBar::handle:vertical {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
    stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));
    min-height: 0px;
}
QScrollBar::add-line:vertical {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
    stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130),  stop:1 rgb(32, 47, 130));
    height: 0px;
    subcontrol-position: bottom;
    subcontrol-origin: margin;
}
QScrollBar::sub-line:vertical {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
    stop: 0  rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130),  stop:1 rgb(32, 47, 130));
    height: 0 px;
    subcontrol-position: top;
    subcontrol-origin: margin;
}
        """)
        self.ui.textEdit.setVerticalScrollBar(self.ui.sbar)
        text = '
'
        sher = """12345
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text...
Sample text..."""
        sher = sher.replace('\n', '
')
        text += sher
        text += '
'
        self.ui.textEdit.setText(text)
        self.ui.textEdit.setStyleSheet("""
            QTextEdit {
                font-size:15px;
                font-family:Vazir FD;
            }
        """)

    ##############################
    ####### Functions ############
    ##############################
    def mousePressEvent(self, event):
        self.oldPos = event.globalPos()

    def mouseMoveEvent(self, event):
        if self.oldPos:
            delta = QPoint (event.globalPos() - self.oldPos)
            #print(delta)
            self.move(self.x() + delta.x(), self.y() + delta.y())
            self.oldPos = event.globalPos()

    def _btnBtn(self):
        print('btnBtn')

    def _exit(self):
        self.close()

    def closeEvent(self, event):
        self.close()

def main():
    app = QtWidgets.QApplication(sys.argv)
    QtGui.QFontDatabase.addApplicationFont(':/res/fonts/Vazir-FD.ttf') #add custom font no install
    QtGui.QFontDatabase.addApplicationFont(':/res/fonts/IranNastaliq.ttf') #add custom font no install
    main = mainUi()
    main.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()


text:
Q: TikZ: Labeled point I'm currently doing:
\node [label=below:crimson]     (crimson) at (0.1,-0.9)   {};
\draw [fill=black] (crimson) circle (1pt);

Is there a way of doing this in one command?

A: Something like this:
\node [label=below:crimson,draw,fill=black,circle,inner sep=0pt,minimum size=2pt] at (0.1,-0.9) {};


text:
Q: Move SharePoint main menu bar to be underneath banner I have designed a custom navigation menu using the term store functionality. Then I have added a banner using the s4 tag on my css file.
Now I want to move my menu to be underneath the bannet. How can I go about this?


text:
Q: ¿Còmo acceder a una pagina web mediante distintos equipos, pero con la misma red Tenemmos 6 computadoras, lo que queremos hacer es abrir nuestra pagina web en todos los equipos que poseemos, pero sin instalar ningun programa, nuestro proyecto es crear una pagina web y dentro de ella meter un formulario; el cual consulte, registre y actualice datos.
Y estamos viendo en donde podemos guardar nuestra base de datos (ejemplo: MySql)

A: Mira son varios puntos a tratar
1.- La pagina web esta alojada en la pc "1" tu quieres que las demás (2,3,4,5,6) puedan acceder a ella no?, Debes en primera desactivar el Firewall de Windows, para que puedan acceder las demás pc´s
2.- Después de ello abre la consola y escribe "ipconfig" ahí te tiene que dar la ip de tu maquina.
3.- Es ip la tienes que poner en los navegadores de las demas paginas, y así estarías ingresando a "localhost" de la maquina donde tienes alojada tu web
4.- Ya solo bastaría que pusieras a ruta adecuada por ejemplo quedaría así
192.168.1.77/Carpeta/index.php
Espero te haya resuelto tu duda saludos :D


text:
Q: Tmux loading multiple enviroments from different files Hello I would like to load multiple environments from different files. For example:
First File builds a session with 1 window and 3 panes.
Second File builds a session with 2 windows first window with 2 panes and second window with one pane.
Like:
tmux -f /path/to/file/basic.conf a

and then after detaching from the first session, i would like to load the same way the other enviroment.
tmux -f /path/to/file/scripting.conf a

but when i fire the second command i will attach to the first session (basic.conf).
But i would expect that when I fire the second script I would attach to the second session.
And tmux ls list only one session.
(The conf files by itself are running with no problem)
How is it possible to have multiple session build trough differnt conf files with tmux, and only with tmux no tmuxinator no tmuxp or anything else?
Or should i have one big conf file which builds everything that now is in muliply conf files?
basic.conf
SESSION_NAME="basic"
FIRST_WINDOW="shells"
SECOND_WINDOW="console"

source ~/.tmux.conf

new-session -s $SESSION_NAME -n $FIRST_WINDOW -d

split-window -h -t $SESSION_NAME
split-window -v -t $SESSION_NAME

new-window -n $SECOND_WINDOW -t $SESSION_NAME

select-window -t $SESSION_NAME:0.0

scripting.conf
SESSION_NAME="script"
FIRST_WINDOW="editor"
SECOND_WINDOW="console"

source ~/.tmux.conf

new-session -s $SESSION_NAME -n $FIRST_WINDOW -d

split-window -v -p 5 -t $SESSION_NAME

send-keys -t $SESSION_NAME:0.0 'cd ~/Code' C-m
send-keys -t $SESSION_NAME:0.0 'vim' C-m
send-keys -t $SESSION_NAME:0.1 'cd ~/Code' C-m
send-keys -t $SESSION_NAME:0.1 C-l C-m

new-window -n $SECOND_WINDOW -t $SESSION_NAME
send-keys -t $SESSION_NAME:1 'cd ~/Code' C-m

select-window -t $SESSION_NAME:0

A: I think I found a solution by myself.
The command:
tmux -f /path/to/file.conf a

should only be used when you would like to load another tmux config file instead of the default one.
If you like to start multiple sessions , which are preconfigured in files, then you have to do something like this:
tmux source-file -q .dotfiles/tmux/enviroments/basic.conf && tmux attach -t basic

Perhaps there is a better solution, but for now this solves my problem.
P.S. i made a little function to load the files less complicated.
function muxload(){

    if [ -f ~/.dotfiles/tmux/enviroments/$1 ]; then
        tmux source-file -q ~/.dotfiles/tmux/enviroments/$1 && tmux attach -t $1
    fi

    if [ -f ~/.dotfiles/tmux/enviroments/$1.conf ]; then
        tmux source-file -q ~/.dotfiles/tmux/enviroments/$1.conf && tmux attach -t $1
    fi

}

run it like this:
muxload {name_of_conf_file}


text:
Q: Display "marked as final" status for a document in SharePoint Online document library view There is a feature inside Word, Excel and PowerPoint to mark a document as final. More info here: https://support.microsoft.com/en-us/office/help-prevent-changes-to-a-final-version-of-a-file-b1af610f-f172-42c9-85fc-a178a503cc81?ui=en-us&rs=en-us&ad=us

Basically you go inside the Office Document go to File > Protect Document > Mark as Final. The next time someone opens that document a message appears at the top stating this document is final.
Is there a way to display that the document has been "marked as final" in the SharePoint Online Document library view? I was not able to find an out-of-the-box metadata column that displays this. Is there a SPFx extension available to do this?
Note: I'm aware that I can add column on the document library called "Final" (Yes/No), this however is clunky as you would think the user marking the document as final would capture some metadata behind the scenes.

A: You can try the following. I did a quick test and seems to work fine.
Create a column of type 'Yes/No' and name the column '_MarkAsFinal' (exactly without quotes). Make the default value as 'No'. Upload a document and mark the document as final. The column should automatically be populated with 'Yes'. You can rename the column based on your requirement after the column has been created.

A: In SharePoint document life cycle is managed through the workflow. You can create a choice column with the value something like Draft, In Progress, Final , so once the document is submitted it will be in Draft mode, then if someone review the document it will be in In Progress or Review mode, and so on... finally we can make document status as Final
The above document life cycle can be managed through the workflow or Microsoft Flow or Nintex workflow.
You can refer to the below below example of document life cycle in SharePoint :
Working Documents and Final Published Documents

A: Thanks sssreddy for the solution with '_MarkAsFinal'. One more useful hint I found out after some troubles getting this solution to work: make sure Library Settings -> Advanced Settings -> Content Types -> 'Allow management of content types' is set to 'YES' and when you create the column UNCHECK 'Add to all content types'.


text:
Q: String with white space being passed incorrectly in a Django template I have a variable called "Vintage White" that I am trying to pass to an attribute of an input element like so.
<input name={{ attribute_value }}>

What I expect is for the element to be rendered like this
<input name="Vintage White">

But instead I get this
<input name="Vintage" white>

How do I pass the entire string with white spaces to the input element so that I get my expected result?

A: You need to use quotation marks, otherwise the value will end before the first space of the attribute_value, so:
<input name="{{ attribute_value }}">


text:
Q: How to build a Scala sequence of tuples from two sequences of tuples? I have two sequences of tuples:
val seqA: Seq[(String, Long)] = Seq(("0", 123), ("1", 10))
val seqB: Seq[(String, Long)] = Seq(("0", 50), ("1", 75))

I need to obtain a new sequence by comparing the value of Long parameters by tuples. The comparison criterion is: if the integer of seqB is strictly greater than the integer of seqA then only the integer of seqB is retained. The comparison algorithm must perform the following task:
For "0", 123 is strictly greater than 50 so we keep 123.
On the other hand, for the value "1", 10 is less than 50 so we eliminate the value.
The desired result is the following:
val result: Seq[(String, Long)] = Seq(("0", 123))

Any help or any ideas?

A: You description is different from the example. You said that you need to leave only greater elements from seqB, but in your example you left only elements from seqA. The solution below is based on the example and gives the result `List(("0", 123)). I hope it will help you.
val seqA: Seq[(String, Long)] = Seq(("0", 123), ("1", 10))
val seqB: Seq[(String, Long)] = Seq(("0", 50), ("1", 75))
seqA.lazyZip(seqB).flatMap {
    case ((aKey, aValue), (bKey, bValue)) if aKey == bKey =>
      if (aValue > bValue) {
        Some((aKey, aValue))
      } else {
        None
      }
    case _ =>
      None // keys don't match, I suppose we need to eliminate element too
  }

Otherwise it can be solved with Map, then you will fix the problem with different keys.
val seqA: Seq[(String, Long)] = Seq(("0", 123), ("1", 10))
val seqB: Seq[(String, Long)] = Seq(("0", 50), ("1", 75))
val seqBMap = seqB.toMap
seqA.filter {
  case (aKey, aValue) => seqBMap.get(aKey).exists(_ < aValue)
}


text:
Q: Is it safe to significantly upscale the image? So say I have 600x600px original jpg image.
But on a page it's displayed significantly upscaled (for example to 25000x25000px), something like:

It also may be slightly scaled further via transform:scale animation, for example:

I don't want to explain why do I do this, as it's not really relevant, but tldr it's served as a placeholder for a tile-based viewer (before tiles are loaded).
My question is, is this a performance concern or no? Can modern browsers safely display/render upscaled image? Or will there be memory problems or something like that (especially on mobile)?
Thank you.

A: It obviously depends on the browser, and the computer. It should be able to upscale like that, but it would be very pixilated and ugly. I don't know why you would want to do that. But yes, it should work.


text:
Q: C++ compile time macros to detect windows os Are there any C++ compile time macros which exists to detect which Windows OS the code is being compiled on. I basically want to support certain functions only on Win7. So I am interested in doing something like this
#if <os_macro> = WIN7
  // This function would do something valid only on Win7 builds.
  bool myfunction {
        // do something here
  }
#else
  // This function would typically return false, since its not supported on OS below win7
  bool myfunction {
       return false;
  }
#endif

Is there any other better way to do this?

A: The OS that it's getting compiled on is not all that important; what matters more is the OS that the code is running on, which you obviously cannot detect at compile time.  But if you want your code to run on older versions of Windows, you can set WINVER and _WIN32_WINNT to certain values, which will cause newer functions not to be available etc. (just search the Windows header files for where those macros get tested to get an idea).
To test for functionality at runtime, use GetProcAddress (and possibly also LoadLibrary, if it's in a newer DLL) to test if the function is available.  If it is, call it, if not, don't.
See also the predefined macros used by the Visual Studio compiler if you want to detect the compiler version etc.

A: There are a set of standard windows header macros to tell you the exact version of the OS

A: There are certain things that do require knowing which OS version at compile time.
For example import "winhttp.dll" will compile under Windows 7, but cause compile time error (C1083) under Windows 10.
But if you switch to import "winhttpcom.dll". It would compile under Windows 10 but fail under Windows 7.
So an OS macro is needed here to import appropriate dll.

A: At least with MS VC++, WIN32, _WIN32, and _WIN32_WINNT, for starters. Unless you need to control it at compile time, you might consider using something like GetVersionEx to detect at run-time, so the same build runs on older versions, but takes advantage of new features when they're available.

A: My response is 10 yrs late but posting the answer for upcoming yrs.
For detecting the version c/c++ compiler version can be used. Suitable macro is mentioned below:
_MSC_VER

_MSC_FULL_VER

Reference: MS macros

A: My two cents for people that want to compile / include differently between CONSOLE and WIN32 App under visual Studio (2017) in my case.
You you use wizard to create a Console App, You will have:
WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)
under:

If You use wizard for win32 GUI App:
WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)
so NO _CONSOLE.

so You can write:
#ifdef _CONSOLE
// for Console
#else
// for GUI

#endif // _CONSOLE

int main()
{
#ifdef _CONSOLE
    // for Console
#else
    // for GUI

#endif // _CONSOLE

    return 0;
}


text:
Q: JSON.Net constructor parameter missing when deserializing I have a simple object that I'm roundtripping through JSON. It serializes just fine, but I deserialize it one of the values is set to the default value (0, in this particular case). Why is that?
Here's my object:
public class CurrencyExchangeRate
{
    public string CurrencyCode { get; private set; }
    public decimal Rate { get; private set; }

    public CurrencyExchangeRate(string currencyCode, decimal exchangeRate)
    {
        this.CurrencyCode = currencyCode;
        this.Rate = exchangeRate;
    }
}

This serializes to JSON as something like {"CurrencyCode":"USD", "Rate": 1.10231}. But when I deserialize it the Rate field is always set to 0. The CurrencyCode field is correctly set, so clearly deserialization is not failing entirely, just the one field is failing.

A: The constructor parameters are named wrong.
Because there is no parameterless constructor, JSON.net is forced to use the constructor with parameters and provide values for those parameters. It tries to match up the fields from the JSON string with the parameters to your constructor by comparing their names. This works for the currency code because CurrencyCode is close enough to currencyCode. But the JSON field name Rate is too different from the constructor parameter exchangeRate, so JSON.net can't figure out that they're the same thing. Thus it passes the default value for that type, 0m in this case. Changing the constructor parameter name to be something like rate will fix the problem.
public class CurrencyExchangeRate
{
    public string CurrencyCode { get; private set; }
    public decimal Rate { get; private set; }

    //NOTE changed parameter name!
    public CurrencyExchangeRate(string currencyCode, decimal rate)
    {
        this.CurrencyCode = currencyCode;
        this.Rate = rate;
    }
}


text:
Q: SQL Server outbound IP address inconsistency in Azure VM I have this setup:

*

*Azure VM (B-series)

*Static public IP

*SQL Server running outside of Azure, with IP whitelisting on the firewall set tot he public static IP of the Azure VM

*Two ASP.NET apps that connect to the SQL Server on the same IP but with different usernames/passwords

Expected:

*

*Both apps can connect to the SQL Server and return data

Actual:

*

*Only one of them can connect to the SQL Server and return data

*Apps running elsewhere with static whitelisted IPs can connect just fine

This is really wierd!  Does Azure sometimes use some other outbound IP address?


text:
Q: Try to use Agent in Webapplication for bytecode Manupulation I'm not that good in Java but I have my webApplication running on a Wildfly.
I have 3 threads who just call a function that insert logs in in and the function saves the logs to a Database and after that every thread sends a time how long did it takes to do this.
They send the data to another programm I wrote what has 3 threads to call one of the 3 server threads.
So now I try to do some ByteCode Manipulation every thread on the server saves the datetime call the log function waits 1 second and returns then the time they needed.
1 Thread write something in an logfile before or after they waitet 1 second.
But this part where they wait a second and call the log function I want that to inject to every 3 threads with Bytecode manipulation.
public class MyTransformer implements ClassFileTransformer {

@Override
public byte[] transform(ClassLoader loader, String className, Class redefiningClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {

    return transformClass(redefiningClass, bytes);
}

private byte[] transformClass(Class classToTransform, byte[] b) {
    ClassPool pool = ClassPool.getDefault();
    CtClass cl = null;
    try {
        cl = pool.get("de.soptim.ws.MyApplication");
    } catch (javassist.NotFoundException e) {
        e.printStackTrace();
    }
    try {

        assert cl != null;
        CtMethod[] methods = cl.getMethods();
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].isEmpty() == false) {
                changeMethod(methods[i]);
            }
        }
        b = cl.toBytecode();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cl != null) {
            cl.detach();
        }
    }
    return b;
}

private void changeMethod(CtMethod method) throws NotFoundException, CannotCompileException {

    if (method.hasAnnotation(Loggable.class)) {
        method.insertBefore("threadLogger.info(\"ADDED THIS FROM BYTECODE !!!\");");
        method.insertAfter("threadLogger.info(\"ADDED THIS FROM BYTECODE !!!\");");
    }
}}

Thats my transformer class it should increase the Code my Methods need it checks what Method has an @Loggable annotation an then adds the code into it("at the moment it's just some log statments for checking if it works")
My biggest problem is now that I don't know how to call my agent ... I googled hwo to call an agent at runtime with agentmain() but I think I dind't really understood how it works.
Agent Class
public class LogAgent  {

public static void agentmain(String agentArgs, Instrumentation inst) {
    System.out.println("Starting the agent");
    inst.addTransformer(new MyTransformer());
}}

Hope you understand My problem :) I and if you answere pleas try to stay noob friendly :D.

A: you don't call your agent explicitly, you should specify additional argument to your JVM :
java -javaagent:jarpath[=options]

where jarpath is a path to jar containing your agent. JVM will invoke premain method before main method of java program.
And transform method will be called before classloading by JVM (you don't call it explicitly).
Last remark : you should implement premain method, not agentmain.
agentmain is used during attaching to running vm, while premain is used when you start JVM with -javaagent method.
And make sure that your jar have valid manifest, as described : https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/package-summary.html
I haven't using javaassit so I cannot say that your code is valid, but instrumenting webapp server like Wildfly is much harder than normal java app (mostly due to classloaders visibility and hierarchy).
See also :
http://www.tomsquest.com/blog/2014/01/intro-java-agent-and-bytecode-manipulation/
Tutorials about javaagents


text:
Q: Bug in Microsoft Cortana Scheduler When using the Microsoft scheduler to set up a meeting with two users outside of your organisation and one inside, if one of the users outside the organisation selects the option "All of those times work for me." Cortana doesn't respond or appear to accept that response at all. In 24 hours it will send a message to the original scheduler along the lines of "I am yet to hear anything back from example@hotmail.com".
Has anyone else come across this issue before? How does Cortana work when trying two schedule meetings with two users outside of the Exchange mailbox domain?


text:
Q: PHP-FPM NGinx Pthreads Linux installation I'm trying to achieve multiple upload functionality (upload to multiple places at once).
I successfully achieved this on windows (XAMPP + PThreads DLL's) but when installing PHP-FPM+php-pecl-pthreads.x86_64, and extending the Thread class i'm getting the error:
include(Thread.php): failed to open stream: No such file or directory

i tried adding all pthreads.so related to the php.ini:
/usr/lib64/php/modules/pthreads.so
/usr/lib64/php-zts/modules/pthreads.so
/usr/lib64/libpthread.so
/usr/lib/gcc/x86_64-redhat-linux/4.4.4/32/libmudflapth.so
/lib64/libpthread-2.12.so

but i'm getting
undefined symbol: core_globals_id in Unknown on line 0

on my phpinfo i see thread safety is disabled.
Did anyone achieve this functionality and can shed some light on how to upload to multiple places at once / installing pthreads successfully on linux.
thanks,
Danny

A: For debian/ubuntu

*

*download php source (make sure you have deb-src)

apt-get source php5

*go to that dir

cd php5*

*go to ext dir

cd ext

*download pthreads

git clone https://github.com/krakjoe/pthreads.git

*rebuild the configure settings

cd .. && ./buildconf --force

*ensure you have pthreads in configure options

./configure --help | grep pthre

*run configure (change the paths as appropriate for your setup)

./configure --enable-debug --enable-maintainer-zts --enable-pthreads --prefix=/usr --with-config-file-path=/etc --with-apxs2=/usr/bin/apxs2 --enable-fpm

*visit this for more info about user/group specific options if you need them.

make -j2
make -j2 install

*Now you will have php compiled with pthreads support. Verify this:

php -m | grep pthreads

*Make init script

copy sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm

*change user and group to the username which nginx use in /etc/init.d/php-fpm.

service nginx restart

*Go to your nginx public foolder

cd <your-nginx-public-folder>

*touch phpinfo.php && echo "<?php phpinfo();" >> phpinfo.php

*go to your browser and search for pthreads in http://<your url>/phpinfo.php just created php file


text:
Q: JavaFx - How to display SimpleStringProperty value in TableView I am busy working through a tutorial and am stuck on one point.
Basically launch new scene and display values from ObservableList of type Person in a table view.
The person class consists of 3 SimpleStringProperty's firsName, lastName and email.
But when I run the app it seems to display the values of the SimpleStringProperty [StringProperty [value:actualvalue]] in the table and not the value of the SimpleStringProperty. If I change the Person's class getFirstName method to return a String firstName.get() then it display the value correctly in the table.
Am I supposed to use the SimpleStringProperty or rather plain objects like String?

The person class
package co.za.chrispie.addressBook;

import javafx.beans.property.SimpleStringProperty;

public class Person {

private SimpleStringProperty firstName;
private SimpleStringProperty lastName;
private SimpleStringProperty email;

public Person(final String firstName, final String lastName, final String email) {
    this.firstName = new SimpleStringProperty(firstName);
    this.lastName = new SimpleStringProperty(lastName);
    this.email = new SimpleStringProperty(email);
}

public String getFirstName() {
    return firstName.get(); //Changes this method to return a String
}

public SimpleStringProperty getLastName() {
    return lastName;
}

public SimpleStringProperty getEmail() {
    return email;
}

}

The Controller class
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.za.chrispie.addressBook;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

public class OracleAddressBookController implements Initializable {

@FXML
TableView<Person> table;
@FXML
TableColumn<Person, String> colFirstName;
@FXML
TableColumn<Person, String> colLastName;
@FXML
TableColumn<Person, String> colEmail;

final ObservableList<Person> data = FXCollections.observableArrayList(
    new Person("Jaco", "Pieters", "jp@me.co.za"),
    new Person("Chrispie", "Pieters", "chrispie@me.co.za")
);

@Override
public void initialize(URL url, ResourceBundle rb) {
    assert colFirstName != null : "fx:id=\"colFirstName\" was not injected: check your FXML file 'OracleAddressBook.fxml'.";
    assert colLastName != null : "fx:id=\"colLastName\" was not injected: check your FXML file 'OracleAddressBook.fxml'.";
    assert colEmail != null : "fx:id=\"colEmail\" was not injected: check your FXML file 'OracleAddressBook.fxml'.";
    configureTable();
}

private void configureTable() {
    colFirstName.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
    colLastName.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
    colEmail.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));

    table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    table.setItems(data);
    assert table.getItems() == data;
}
}

and the front end FXML
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="500.0" prefWidth="600.0"    styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml"  fx:controller="co.za.chrispie.addressBook.OracleAddressBookController">
<children>
  <Label layoutX="14.0" layoutY="11.0" text="Address Book" />
  <TableView fx:id="table" layoutX="14.0" layoutY="35.0" prefHeight="451.0" prefWidth="572.0">
  <columns>
    <TableColumn prefWidth="75.0" text="First Name" fx:id="colFirstName" />
    <TableColumn prefWidth="75.0" text="Last Name" fx:id="colLastName" />
    <TableColumn prefWidth="75.0" text="Email" fx:id="colEmail" />
  </columns>
</TableView>
 </children>
  <stylesheets>
   <URL value="@oracleaddressbook.css" />
 </stylesheets>
</AnchorPane>

A: You need to change the name of your property getters to nameProperty(), where name is your property. So you would have firstNameProperty() and emailProperty().
getName() works, but the table won't observe the property's changes.
The doc for PropertyValueFactory explains this subject:

In this example, the "firstName" string is used as a reference to an assumed firstNameProperty() method in the Person class type (which is the class type of the TableView items list). Additionally, this method must return a Property instance. If a method meeting these requirements is found, then the TableCell is populated with this ObservableValue . In addition, the TableView will automatically add an observer to the returned value, such that any changes fired will be observed by the TableView, resulting in the cell immediately updating.
If no method matching this pattern exists, there is fall-through support for attempting to call get() or is() (that is, getFirstName() or isFirstName() in the example above). If a method matching this pattern exists, the value returned from this method is wrapped in a ReadOnlyObjectWrapper and returned to the TableCell. However, in this situation, this means that the TableCell will not be able to observe the ObservableValue for changes (as is the case in the first approach above).


text:
Q: From PHP to vb.net; How to transfer a text from one page to another in Visual Basic Asp.net so I am a web developer who is used to PHP and MySQL and now my company is switching completely to VB.Net. I am using Visual Studio 2010 for development.
How would best would I accomplish displaying the text from one page sent using a GET method of a form on a different page?
What I would like to do is:
Page 1, have a list of buttons, and depending on which button I click a name is sent to the next page.
Page 2 receives the name and displays the name in a textbox or some other form field.
Also, any resources that might help me quickly learn the ins and outs of vb.net.
I am familiar with Visual basic and have coded in it before, but never in a .net environment.
Thanks!

A: on first page
<a href="OtherPage.aspx?Parameter=myParameter" >

then in the code behind for OtherPage.aspx in Page_Load
Dim query as String = Request.QueryString("Parameter")
myLabel.Text = query

in the XHTML in OtherPage.aspx you would see
<asp:Label ID="myLabel" runat="server" ></asp:Label>

A: You can read some examples here
http://www.codeproject.com/Articles/5876/Passing-variables-between-pages-using-QueryString
http://www.aspdotnet-suresh.com/2012/10/query-string-in-aspnet-example-c-vbnet.html?m=1


text:
Q: Unpacking an array in a function call Is there a way to unpack an array as arguments for a function?
For example in python if I have:
user = ["John", "Doe"]

def full_name(first_name, last_name):
    return first_name + last_name

Then full_name(*user) unpack my user array and pass each of its items as argument of full_name.
Is that possible to achieve such a behavior in JavaScript/TypeScript?

A: You want the ...spread operator.
const user = ["John", "Doe"] as const

function fullName(firstName: string, lastName: string): string {
    return firstName + lastName
}

fullName(...user)

Note the as const.
In order for this to have type safety in Typescript, the array needs to be a two item tuple of type [string, string] and not just an array of unknown length like string[]. This is because in order to guarantee type safety there must be at least 2 strings in that array in order to satisfy both arguments. as const forces typescript to treat that array as a tuple with known strings and length instead.
Playground

A: You could either apply array desctructuring on the parameter of the full_name function:
const user = ["John", "Doe"];

const full_name = ([first_name, last_name]) =>
    first_name + last_name;

full_name(user);

or use the spread operator (...) when you call full_name with the array parameter.
const user = ["John", "Doe"];

const full_name = (first_name, last_name) =>
    first_name + last_name;

full_name(...user);

A: Try Destructuring assignment. Like this:
const full_name = (arr) => {
    const [firstname, lastname] = arr;
    return `${firstname} ${lastname}`;
};

var user = ["John", "Doe"];
console.log(full_name(user)); // result: John Doe

A: This can be achieved using the ... (spread) operator.
const user = ["John", "Doe"]

function fullName(firstName, lastName) {
    return firstName + ' ' + lastName;
}

fullName(...user);


text:
Q: Java Maven Project with Owner Library using multiple properties file across a shared project I am trying to pass in property files from other projects using the Owner library. I currently have the following Java Maven projects:

*

*Core

*Project A

*Project B

Inside the Core project I have methods that require the use of URLs via a properties file stored in the Core directory. However, after the introduction of new projects, I will now need to pass project related property file into the core e.g. Project A properties file into the Core, so that the core can access the correct urls.
I am using the Owner Java library to handle property files. I currently have a similar setup to the following inside the core project:
import org.aeonbits.owner.Config;

public interface MyConfig extends Config {
    int port();
    String hostname();
    @DefaultValue("42")
    int maxThreads();
}

// Example of it being used
MyConfig config = ConfigCache.getOrCreate(MyConfig.class);
System.out.println(config.port);

The problem lies in sending new property files. In order to send a new property file, I must provide paramaters to the methods used in the core project.
myMethodFromCore(ConfigFileNameFromAnotherProject config)
config.homeUrl();

If the above example code is a method inside the core, then it must be familiar with ConfigFileNameFromAnotherProject. However, this is not possible since ConfigFileNameFromAnotherProject will live inside a Project A / Project B, thus will not be recognised in the core. Does anyone have any neat solution or ideas on how I can solve this problem?
Thank you

A: Overall I should mention that using third-party library properties to inject a value into your project is a weird situation to me, I'd suggest thinking twice if you really need to use another library to override your config, as it seems like a vulnerability as you're not in control of your configuration.
Anyway it's not what is being asked, here is my suggestion:
You could try using the reflection if you know your method names:
 Method method = config.getClass().getMethod("getHomeUrl");
 Object invokeResult = method.invoke(config);
 invokeResult.toString();

The thing here is that you need to know the method name you're trying to use.


text:
Q: NPE inside robotium I have to fight some flaky tests and am stuck at one exception I sometimes get with robotium
Caused by: java.lang.NullPointerException
at com.jayway.android.robotium.solo.ViewFetcher.getTopParent(ViewFetcher.java:44)
at com.jayway.android.robotium.solo.PublicViewFetcher.getTopParent(PublicViewFetcher.java:6)
at com.jayway.android.robotium.solo.ViewFetcher.getTopParent(ViewFetcher.java:46)
at com.jayway.android.robotium.solo.PublicViewFetcher.getTopParent(PublicViewFetcher.java:6)
at com.jayway.android.robotium.solo.ViewFetcher.getTopParent(ViewFetcher.java:46)
at com.jayway.android.robotium.solo.PublicViewFetcher.getTopParent(PublicViewFetcher.java:6)
at com.jayway.android.robotium.solo.ViewFetcher.getTopParent(ViewFetcher.java:46)
at com.jayway.android.robotium.solo.PublicViewFetcher.getTopParent(PublicViewFetcher.java:6)
at com.jayway.android.robotium.solo.ViewFetcher.getTopParent(ViewFetcher.java:46)
at com.jayway.android.robotium.solo.PublicViewFetcher.getTopParent(PublicViewFetcher.java:6)
at com.jayway.android.robotium.solo.ViewFetcher.getTopParent(ViewFetcher.java:46)
at com.jayway.android.robotium.solo.PublicViewFetcher.getTopParent(PublicViewFetcher.java:6)
at com.jayway.android.robotium.solo.ViewFetcher.getTopParent(ViewFetcher.java:46)
at com.jayway.android.robotium.solo.PublicViewFetcher.getTopParent(PublicViewFetcher.java:6)
at com.jayway.android.robotium.solo.ViewFetcher.getTopParent(ViewFetcher.java:46)
at com.jayway.android.robotium.solo.PublicViewFetcher.getTopParent(PublicViewFetcher.java:6)
at query.Query.rootViews(Query.java:113)
at query.Query.executeQuery(Query.java:29)

this is the getTopParent method from robotium:
/**
 * Returns the absolute top parent {@code View} in for a given {@code View}.
 *
 * @param view the {@code View} whose top parent is requested
 * @return the top parent {@code View}
 */

public View getTopParent(View view) {
    if (view.getParent() != null // line 44
            && view.getParent() instanceof android.view.View) {
        return getTopParent((View) view.getParent()); // line 46
    } else {
        return view;
    }
}

as far as I see this would mean that view.getParent() changes between the null-check and the recursive call from a view to null?
I could imagine making a pull request to robotium changing the getTopParent to:
/**
 * Returns the absolute top parent {@code View} in for a given {@code View}.
 *
 * @param view the {@code View} whose top parent is requested
 * @return the top parent {@code View}
 */

public View getTopParent(View view) {
            final ViewParent parent = view.getParent();
    if (parent != null && parent instanceof android.view.View) {
        return getTopParent((View) parent);
    } else {
        return view;
    }
}

but I would like to have some more opinions before this.

A: this change is now on the robotium master:
https://github.com/RobotiumTech/robotium/commit/a004cf8cd012709b606590079d5667e519c0d25b
https://github.com/RobotiumTech/robotium/commit/f6b8c9998bf1fe04dd7ff838aab7cdb703cc483e
more context:
https://groups.google.com/forum/#!topic/robotium-developers/egAxzgsRYZI


text:
Q: Exporting Linkedin Learning Video source to .txt file I am very new to python, and programming in general.
I am trying to scrape a LinkedIn Learning web page to locate the full file path for the video on the page.
Ideally, I would like the script to be able to accept a course url and cycle through each video in the course, to pull the video file path from each video page within the course.
From reviewing the source, I found the area I am interested in is as follows:
<div> data-vjs-player etc etc </div>
Within this div, there is a video element. Within this element, is a src callout which contains the video link I am looking for, example as follows:
<video id="vjs_video_3_html5_api" class="vjs-tech" preload="auto" poster="https://media-exp1.licdn.com/dms/image/C4E0DAQEEM3rME8wwFw/learning-public-crop_675_1200/0?e=1595858400&v=beta&t=V5KkqHuGqUTliAMbL7oUBXeEWcrfBDdi4QrZbyGyAWE" src="https://files3.lynda.com/secure/courses/614299/VBR_MP4h264_main_HD720/614299_00_02_XR15_exfiles.mp4?0pnG4-hMq6_WSlXmJvkGQa6ubLk5EIuE8SG-D0jd9RJOztR5jY8wmlBcsWjHLzBK22z6DydJXGoV8njYeJ_A-dMb6BIZrtkZdUq20t2tD6hxhdNKeWVvik7aOfN3Oyv78_wqePFK1rGmujQnzbCYudW9r0Oyl54EcFQhUqUFnGpkVqHLgQ_Gndo"></video>
I attempted to utilize the following code as a basis, following a BeautifulSoup tutorial to parse the website link for the src callout:
from bs4 import BeautifulSoup
from lxml import html

import requests

URL = 'https://www.linkedin.com/learning/python-essential-training-2/about-python-3?u=2154233'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html5lib')

results = soup.find(id="vjs_video_3_html5_api")
print(results.prettify())

However, it is at this point I have come to a standstill, as I do not understand where to go here, despite researching this to the best of my abilities at this current time.
I really would appreciate any help or guidance that you may be able to provide on this.
Thank you all in advance.

A: When you look at source HTML (for example print(soup)), you will see that the class of <video> tag is different.
You can extract the video url with this example:
import json
import requests
from bs4 import BeautifulSoup

url = 'https://www.linkedin.com/learning/python-essential-training-2/about-python-3?u=2154233'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
data = json.loads(soup.video['data-sources'])
print(data[0]['src'])

Prints:
https://files3.lynda.com/secure/courses/614299/VBR_MP4h264_main_SD/614299_00_03_XR30_aboutpy.mp4?jNwDi0oWUMSPUqh0j6w7yy2IDyBgoGZEeY9Tj2TKVmZmpSMisIoXxG9K1BbRELSP_pM9ySZOFiOq6TzNFvxhEWoGujEGQYT7TfRhuXGwJyGffd5uWTdYBCoc65J-YJuvdg7xijnaDwVjFuUKSAJZxqvYyq8f5nOZrE0Mgckk-1XANfovQ8E


text:
Q: ORMlite alter primary key is there a way, to change the primary key of ORMlite defined databases ?
i'm having a class User with
@DatabaseField(columnName = NAME_FIELD_NAME, canBeNull = false, id = true)
private String name = "";

and i query it with DAO.querybyid(String name);
But when i try to alter the name in the database, it doesn't give me any warnings, will ORMLite alter the table column and remove the index, and then update the column and place the index again ?
I don't think so heh ? so need a workaround :( but also want the DAO.querybyid() advantage to get the user by String.
Can someone help me ?

A:
will ORMLite alter the table column and remove the index, and then update the column and place the index again ?

I assume you are altering your schema using the dao.rawExecute(...) method?  ORMLite doesn't do anything magical with this statement -- it just sends it to the underlying database.  So if you are asking for the field name but it's been renamed to be id then the DAO will not work since it doesn't correspond to the database.  It will do a "SELECT name, ... FROM ..." and get a SQL error.
What you can do is have two different versions of the class.  The first one has it with the "old" field-name and the new one has it with the "new" name.  Then if you detect that you need to update the schema, you can issue the raw ALTER SQL statements, and then start using the DAO corresponding to the new version of the class.


text:
Q: Can't access static files with a URL-encoding characters in the names On my CDN, I have some old files with names that were created using rawurlencode function. E.g. one of the files has this name:
Cat%20presentation.pdf
Now, when I try to read this file, I get a "File not found" error:
GET cdn.example.com/documents/Cat%20presentation.pdf

I believe that's because of the encoded space character in the name - %20. For the browser (and the CDN) what I'm asking for is this:
Cat presentation.pdf
while the "%20" part is actually in the filename.
Is there any way I can get around this and access the file?

A: You need to URL-encode the "%" character into "%25":
GET cdn.example.com/documents/Cat%2520presentation.pdf

But if I were you I'd just fix their filenames instead.


text:
Q: Android Recyclerview Remove Animation Is Applied To All Items Strange Behaviour I am using following library to animate items in my recyclerview on removal
https://github.com/wasabeef/recyclerview-animators
I am trying to apply slide to right animation to only removed item but for some reason all items in recyclerview disappears first and then animated back to their position strangely.
Please watch the following video.

Here is my code its very simple:
   friends_screen_friendlist_recyclerview.itemAnimator = SlideInRightAnimator()
                   friends_screen_friendlist_recyclerview.itemAnimator?.apply {
                        addDuration = 120;
                       removeDuration = 1000;
                        moveDuration = 500;
                        changeDuration = 500;
                   }
    friendItems.removeAt(0)

               friends_screen_friendlist_recyclerview.adapter!!.notifyItemRemoved(0)

Adapter class:
class FriendListAdapter(val items : ArrayList<FriendListItem>, val context: Context,val listener:FriendListListener) : androidx.recyclerview.widget.RecyclerView.Adapter<FriendListViewHolder>(),Filterable {

    var filterItems = ArrayList<FriendListItem>()

    init{
        filterItems = items
    }
    // Gets the number of animals in the list
    override fun getItemCount(): Int {
        return filterItems.size
    }
    override fun getItemViewType(position: Int): Int {
        return position
    }

    override fun getFilter(): Filter {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence?): FilterResults {
                val charSearch = constraint.toString()
                if (charSearch.isEmpty()) {
                    filterItems = items
                } else {
                    val resultList = ArrayList<FriendListItem>()
                    for (row in items) {
                        if (row.userName.toLowerCase(Locale.ROOT).contains(charSearch.toLowerCase(Locale.ROOT))) {
                            resultList.add(row)
                        }
                    }
                    filterItems = resultList
                }
                val filterResults = FilterResults()
                filterResults.values = filterItems
                return filterResults
            }

            @Suppress("UNCHECKED_CAST")
            override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
                filterItems = results?.values as ArrayList<FriendListItem>
                notifyDataSetChanged()
            }

        }
    }

    // Inflates the item views
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendListViewHolder {
        return FriendListViewHolder(LayoutInflater.from(context).inflate(R.layout.friendlist_item, parent, false))
    }

    // Binds each animal in the ArrayList to a view
    override fun onBindViewHolder(holder: FriendListViewHolder, position: Int) {
        //holder?.profileImage?.background = items[position].profileImage
        holder?.userName?.text = filterItems[position].userName
        holder?.level?.text = "Seviye "+filterItems[position].level

        // do the necessary profilePic checks.
        Picasso.get().load(filterItems[position].profileImage).into(holder?.profileImage, object : Callback {
            override fun onSuccess() {
                listener.onProfilePicLoaded()
            }

            override fun onError(e: Exception?) {
                listener.onProfilePicLoaded() // error but anyway. just tell messages class its loaded so it can show the page.

            }
        })

  if(filterItems[position].gender == 0){
            holder?.gender?.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.male_icon))
        }else{
            holder?.gender?.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.female_icon))

        }

        if(filterItems[position].isOnline){
            holder?.isOnline?.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.online_circle))
        }else{
            holder?.isOnline?.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.offline_circle))

        }

        holder.itemContainer.setOnClickListener {
            listener.onFriendSelected(filterItems[position])

        }
        holder.itemContainer.setOnLongClickListener {
            listener.onFriendSelectedAndHolded(filterItems[position],position)
            Log.d("yunusdebug","long")

            return@setOnLongClickListener true

        }

    }

}

class FriendListViewHolder (view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) {
    // Holds the TextView that will add each animal to
    val itemContainer = view.friendlist_item_container

    val userName = view.friendlist_item_username_textview

    val level = view.friendlist_item_level_textview
    val isOnline = view.friendlist_item_isOnline
    val profileImage = view.friendlist_item_profile_image
    val gender = view.friendlist_item_gender

}

A: When you remove an item in your adapter you should also notify the new range. Please try the following:
friendItems.removeAt(index)
notifyItemRemoved(index)
notifyItemRangeChanged(index,friendItems.size)


text:
Q: Stability testing of REST API I have a registration REST API which i want to test as  -
Register 15000 users and pound the server with repeated incident reports (varying traffic with max being 100 per minute, min being 1 per 24 hrs and avg being one per minute ) over a period of 48 hours.
Which tool can I use to test stability of my REST API?

A: For pounding the server with incidents over a period of time, you can use http://runscope.com/ .
It is helpful for testing APIs. You can just trigger events in runscope over a period time or schedule it to hit the server as required.


text:
Q: Use Like% in CouchDB Doctrine Symfony 2 I'm using this bundle and I wanto to find my element by %LIKE% mysql
My document is like this:
{
   "_id": "60a403542a2b7d44bf84ed569d1e6efe",
   "_rev": "1-9e1ed380dd91ac8c835ef0f8e152f0a8",
   "type": "mytype",
   "doctrine_metadata": {
       "indexes": [
           "name",
       ]
   },
   "name": "barfoo",

}

I want to Find all element that begin with barfo
I saw this link, but I don't know if this is a right Solution.
How Can I do Like query in couchDb + symfony2 ?

A: There aren't %Like% in couchDb (1.6.1), but you can use startkey and endkey.
You have to create a view like:
function (doc) {
    if (doc.type = 'myType') {
        emit(doc.name, doc.name);
    }
}

with name for example people.
For example and simplicity
Designname = people
viewname = people

After that you can do This Curl
curl -X GET 'http://localhost:5984/db/_design/people/_view/people?startkey="foo"&endkey="foo\ufff0"'

In this way you can find all element that begin with foo.
Why \ufff0 ? Check this link

String Ranges
If you need start and end keys that encompass every string with a
  given prefix, it is better to use a high value unicode character, than
  to use a 'ZZZZ' suffix.
That is, rather than:
startkey="abc"&endkey="abcZZZZZZZZZ" You should use:
startkey="abc"&endkey="abc\ufff0"

How Can you do this in Symfony ?
If you want to create View by Symfony
You can Create the view in yourapp/AppBundle/CouchDocument/View/PeopleView.php
<?php

namespace yourapp\AppBundle\CouchDocument\View;

use Doctrine\CouchDB\View\DesignDocument;

class PeopleView implements DesignDocument
{

    public function getData()
    {
        $people = <<<'JS'
function (doc) {
        if (doc.type = 'myType') {
            emit(doc.name, doc.name);
        }
    }
JS;

        return array(
            'views' => array(
                'people' => array(
                    'map' => $people,
                ),
            )
        );

    }
}

and in your controller you can do something like this
/**
 * @Route("/testPeople/{code}", name="test_people")
 * @Method({"GET"})
 * @Template("myAppBundle:People:test_query.html.twig")
 */
public function testPeopleAction($code)
{

    $dm = $this->container->get(
        'doctrine_couchdb.odm.default_document_manager'
    );
    $peopleView = new PeopleView();
    $client = $this->container->get('doctrine_couchdb.odm.default_document_manager');
    $view = $client->createDesignDocument('people', $peopleView);

    $relatedObjects = $dm->createNativeQuery('people', 'people')
        ->setStartKey($code)
        ->setEndKey($code . "\xEF\xBF\xB0")
        ->execute();
    $a = array();
    foreach ($relatedObjects as $doc) {
        $a[] = $doc['value'] //it is your results
    }

    return array(
        'results' => $a
    );
}

I saw the unitTest inside vendor/doctrine/couchdb/tests/Doctrine/Tests/CouchDB/CouchDBClientTest.php to find something to usefull
I Don't Know if it is the best way, but for me it works :)


text:
Q: linux and shared libraries and different g++ compilers What is the story regarding having a process on Linux, which dlopen() multiple shared libraries and the executable and/or the shared libraries compiled with different C++ compilers (e.g. provided by customers or 3rd parties).
Am I going right in the following assumptions:

*

*there is only a single namespace for symbols in a linux process. Symbols are found and resolved only by symbol name. The source of the symbol is random in the presence of an unknown executable (customer supplied) or customer supplied shared libraries.

*there is no way to make certain, that STL/boost symbols are being resolved from the correct source, as they are always weak and thus might be overwritten.

What are the implications of using multiple copies of (different) libc++ inside the same process (some of them static)?
I don't expect seperate libraries to be able to talk to each other via a C++ interface but only via a C interface. What I would like is, that one can load SharedLibraries from different vendors into a single process and they do not screw up each other.
I know that this has worked in Windows for decades

A: Your comment completely changes your question:

I don't expect it to be able to talk to each other via a C++ interface but only via a C interface. What I expect is, that one can load SharedLibraries from different vendors into a single process and they do not screw up each other. (This btw is working on Windows since decades)

This element of behaviour is largely system indipendant.  The Windows PE format and Linux ELF are similar enough in design that they don't add any additional constraints or capabilities on this topic.  So if your technique was going to work in Windows then it should also do so in Linux, just replacing .dll files for .so files.
Linux has more standardisation around calling conventions than Windows, so if anything you should find that Linux make's this simpler.

Origional Answer
Question:

there is only a single namespace for symbols in a Linux process?

That's correct; there's no such thing as namespaces in Linux's loader.
As you may know, C and C++ are very different languages.  C++ has namespaces C does not.  When libraries are loaded (in both Linux, Unix and also Windows) there is no concept of namespace.
C++ compilers use name mangling to ensure that names isolated by namespaces in your code, do not compiled when placed as symbols in the shared object. C compilers don't do this and don't need to do it because there are no namespaces.

Question:

Symbols are found and resolved only by symbol name. The source of the symbol is random in the presence of an unknown executable (customer supplied) or customer supplied shared libraries.

Let's replace the word "random" for unpredictable.  That's also correct.  From Wikipedia:

The C++ language does not define a standard decoration scheme, so each compiler uses its own. C++ also has complex language features, such as classes, templates, namespaces, and operator overloading, that alter the meaning of specific symbols based on context or usage. Meta-data about these features can be disambiguated by mangling (decorating) the name of a symbol. Because the name-mangling systems for such features are not standardized across compilers, few linkers can link object code that was produced by different compilers.

Question:

What is the story regarding having a process on LINUX, which dlopen() multiple shared libraries and the executable and/or the shared libraries compiled with different C++ compilers (e.g. provided by customers or 3rd parties).

You can off course dlopen() a shared object, but dlsym() would be tricky to use because of name mangling.  You'd have to inspect the shared object manually to determine the precise symbol name.

What are the implications of using multiple copies of (different) libc++ inside the same process (some of them static)?

If you got that far, then I'd be concerned about memory management first of all.  libc++ is responsible for implementing new and delete and converting these  into memory requests from the OS.  If they behave anything like GNU's malloc() and free(), they might manage their own pool of memory.  It'd be hard to prectict what would happen if you called delete on an object that was created by a different libc++.

A: it seems that parts of this randomness can be avoided by loading the shared libraries using the following flags passed to dlopen():

*

*RTLD_LOCAL

*RTLD_DEEPBIND