text:
Q: The token '&&' is not a valid statement separator in this version On the way of installing Webpack on my React Project, the following problem hinders my progress:
last step to configure the Webpack
npm run build && node ./dist/main.js

Error on Windows Power Shell / on Visual Studio Code
PS C:\Users\pythonbuddha\Desktop\to_experiment\to-do-list> npm run build && node ./dist/main.js
At line:1 char:15
+ npm run build && node ./dist/main.js
+               ~~
The token '&&' is not a valid statement separator in this version.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidEndOfLine

Tutorial which promised to configure the webpack
https://developerhandbook.com/webpack/webpack-4-from-absolute-scratch/

https://developerhandbook.com/webpack/how-to-configure-scss-modules-for-webpack/

A: It's because you're in PowerShell, try running it in CMD or Git Bash
Alternatively (if you wish to continue in PS):
(npm run build) -and (node ./dist/main.js)

3rd Alternative, just run them separetly,

A: The && operator is used in linux bash to run both commands after each other. (Also if the first command fails, the second won't be executed)
This does not work in PowerShell on Windows so just split both commands and run them separately:
npm run build
node ./dist/main.js

For completeness, Powershell can behave the same when you do (command1) -and (command2) and && might actually work depending on your PowerShell version.
See this for further info: https://stackoverflow.com/a/564092/2232127

A: I found that within PowerShell as my terminal within VS Code, replacing && in the command with ; did the trick.

A: PowerShell (Core) v7+  - but not Windows PowerShell - now does support && and ||, the pipeline-chain  operators, so your command should work as-is there - see this answer for PowerShell-specific considerations for their use; see below for Windows PowerShell workarounds.
Conceptual note:

*

*In all shells that support it (notably cmd.exe and POSIX-compatible shells such as Bash), && conditionally sequences commands: it executes its RHS command only if the LHS command indicated success; || is the inverse: it executes the RHS only if the LHS indicated failure.

*This is important for preventing execution when it makes no sense to do so; e.g., in npm run build && node ./dist/main.js it only makes sense to run what was just built (with node) if the build succeeded, which is what && ensures.
Windows PowerShell workarounds:
The most succinct workaround:
npm run build; if ($?) { node ./dist/main.js }

This builds on the automatic $? variable, which is a Boolean indicating whether the most recent command succeeded.
The most robust workaround, needed if the commands use 2> redirections:
npm run build; if ($LASTEXITCODE -eq 0) { node ./dist/main.js }

Basing the success test on the automatic $LastExitCode variable, which reflects the process exit code of the most recently executed external program, avoids problems in Windows PowerShell[1] where the presence of stderr output in combination with redirecting it via 2> mistakenly sets $? to $false even when the process exit code is 0.

[1] The problems with 2> redirections are summarized in this answer. They also plague PowerShell (Core) up to version 7.1

A: I have solved the issue by upgrading powershell and renamed dir. path folder name by removing spaces. Now it works properly.
Powershell upgradation link
https://github.com/PowerShell/PowerShell/releases/tag/v7.2.0-preview.8

A: Since some people might arrive here in the same manner as I did, wondering why PowerShell would not allow me to perform a conditional AND operator between two variables within an if statement.
I solved it by evaluating the Left Condition with an If condition, and then the Right Condition immediately within the first true condition.
Example that produced the error:
$Path = "C:\\Temp\test"
$RootPath = "C:\\Temp"
$currentChildren = Get-ChildItem -Force -LiteralPath $Path
$isEmpty = $currentChildren -eq null

if ($isEmpty && $Path -ne $RootPath) {
    Remove-Item -Force -LiteralPath $Path
    }

$foo = "question"
$bar = "answer"

Example that I used to solve the problem:
$Path = "C:\\Temp\test"
$RootPath = "C:\\Temp"
$currentChildren = Get-ChildItem -Force -LiteralPath $Path
$isEmpty = $currentChildren -eq null

if ($isEmpty) {
    if ($Path -ne $RootPath) {
        Remove-Item -Force -LiteralPath $Path
        }
   }

A: Having this issue on the Windows terminal. Solution is to use ; instead && like:
git fetch --all ; git add --all ; git commit -m 'updating things' ; git push


text:
Q: Mini cart in header using divi is not getting updated on changing the cart items count: I am having a wordpress site which is using the Divi theme. When I update the number of items in the cart, the mini cart on the header is not getting updated accordignly. However, the number of items in the mini cart are getting updated on re-loading the page.
Divi is using the below function for updating the cart,
if ( ! function_exists( 'et_show_cart_total' ) ) {
       function et_show_cart_total( $args = array() ) {
               if ( ! class_exists( 'woocommerce' ) || ! WC()->cart ) {
                       return;
               }

               $defaults = array(
                       'no_text' => false,
               );

               $args = wp_parse_args( $args, $defaults );

               $items_number = WC()->cart->get_cart_contents_count();

               $url = function_exists( 'wc_get_cart_url' ) ? wc_get_cart_url() : WC()->cart->get_cart_url();

               printf(
                       '
                               %2$s
                       ',
                       esc_url( $url ),
                       ( ! $args['no_text']
                               ? esc_html( sprintf(
                                       _nx( '%1$s Item', '%1$s Items', $items_number, 'WooCommerce items number', 'Divi' ),
                                       number_format_i18n( $items_number )
                               ) )
                               : ''
                       )
               );
       }
}

How can I update the mini cart on updating the number of items in the cart on ajax call?
Please can anyone help?

A: I fixed the issue by adding the below in my functions.php:
add_filter( 'woocommerce_add_to_cart_fragments', 'your_custom_functions', 10, 1 );

function your_custom_functions( $fragments ) {
    $fragments['.your_cart_class'] = '' . WC()->cart->get_cart_contents_count() . ' Items';
    return $fragments;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Listen to another message only when I am done with my current message in Kafka I am building a Springboot application using Spring Kafka where I am getting messages from a topic. I have to modify those messages and then produce them to another topic. I don't want to consume any other message till I have processed my current one. How can I achieve this?
@KafkaListener(
            topics = "${event.topic.name}",
            groupId = "${event.topic.group.id}",
            containerFactory = "eventKafkaListenerContainerFactory"
    )
public void consume(Event event) {
        logger.info(String.format("Event created(from consumer)-> %s", event));
}

"event" is a json object which I am receiving as a message.

A: See https://docs.confluent.io/platform/current/installation/configuration/consumer-configs.html#consumerconfigs_max.poll.records:

max.poll.records

The maximum number of records returned in a single call to poll().

Type: int

Default:  500

With Spring Boot you can configure it as this property:
spring.kafka.consumer.maxPollRecords

So, you set it to 1 and no more records are going to be polled from this consumer until you return from your @KafkaListener method.


text:
Q: Extending CSS classes Is there any possibility to extend exists class using only css?
.darkStyle {
       color:#eee;
       background:#222;
 }
.element {

       // here I want to get all properties from darkStyle

       min-width:100px;
       display:block;
}

I know that i can use in HTML class="darkStyle element" but any extend method like in my example will be more usable.

A: Use Less or Sass for that.
In Less:
.element {
   .darkStyle; // Will output all styles from .darkStyle;
   min-width:100px;
   display:block;
}

A: Assign the common properties first, then assign the unique properties for .element. This would be the only way with CSS only. You can use CSS frameworks like Less for added features like inheritance.
.darkStyle, .element {
    color:#eee;
    background:#222;
}

.element {
   min-width:100px;
   display:block;
}

A: No you can't "extend" classes. And you don't need to, CSS isn't a programming OO language and has different mechanisms.
For example, classes can be combined on a given HTML element:

  I'm styled by styles applying to .darkStyle

  I'm styled by styles applying to both .darkStyle and .element

Multiclass!


text:
Q: CSS 'absolute' positioning: what is the behavior when there is no non-static ancestor? The definition of 'absolute' positioning is: "The element is positioned relative to its first positioned (not static) ancestor element".
My question is how does the element behave when all ancestors are 'static'?
Can we say that in this case, 'absolute' positioning behave as 'fixed' positioning?

A:
Can we say that in this case, 'absolute' positioning behave as 'fixed' positioning?

No, not entirely. The behavior is the same with respect to the top, right, bottom and left offsets, but not with respect to scrolling, which is what distinguishes fixed positioning from regular absolute positioning.
When there are no positioned ancestors, the containing block of elements with position: absolute is the initial containing block.
The containing block of elements with position: fixed is the viewport, not the initial containing block. The viewport does not move when scrolling, but the initial containing block does (because it can be larger than the viewport), which is why fixed-positioned elements do not scroll with the page, but elements with position: absolute do, even when the latter have no positioned ancestors.
You can manipulate the page layout such that the content scrolls but the initial containing block never does, resulting in a hack that makes position: absolute with no positioned ancestors behave like position: fixed, even in Internet Explorer 6.


text:
Q: Host based firewall in NAT environments Hi getting straight to the point. I am currently working on the architecture of a Host based firewall.
My question/pain point is what happens to these(Host Based Firewalls) when LAN-LAN NAT rules are enabled on physical routers. So if a LAN1 : Machine A wants to contact LAN2 : Machine B it will go via a router R1 and this router with SNAT the IP of the incoming packet from Machine A therefore, Machine B will never know the IP of Machine A which further implies that it wont be able to create any IP based rules for traffic coming from Machine A.
Is there a solution to this problem? Is my understanding of NAT environment correct?
=====THE PROBLEM=====
I have two machines sending there network activity logs to a central server, based on these logs I create firewall policies and sync them to endpoints. So the log from Machine A for the packet going from Machine A to Machine B will have Machine A's local IP but when it is received at Machine B it will have the Router's IP. Therefore, the logs that I receive for this connection from A and B will never be justified and my policies will not work.
I am looking for a solution/workaround for this scenario where i can either map the Routers IP to the original source IP or know at Machine A itself that this particular outgoing packet will get SNAT to Router's IP.


text:
Q: How to install window 7 without formatting my D:drive (that contains my personal data _not OS file)? I know how to backup C:drive as win7 creates window.old file as backup but what if have to backup my other drive ((partition)) and install win7 without harming my data in that drive.

A: If you have 1 physical hardrive with 2 partition or 2 physical hardrive, during installation you can select and format only the drive C: or the hardrive you want to install the OS so that your drive D: with your backup will be safe.
You may want to rename your backup drive so that you can specify that drive during installation.


text:
Q: ADFS 2.0 token expiration time I am caching a token issued by a ADFS 2.0 on the client and use it several times when calling the service.
In the production environment I want to ensure that the token a client can cache expires after a few minutes.
I have read that the token from the ADFS 2.0 expires after 10 hours, but I can't find a place where I can change the expiration time of a token for a relying party.
This is how I currently request a token from the STS:
WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(binding, http://adfs/adfs/services/trust/13/windows");

trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
WSTrustChannel channel = (WSTrustChannel)trustChannelFactory.CreateChannel();
RequestSecurityToken rst = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);

rst.RequestDisplayToken = true;
rst.AppliesTo = new EndpointAddress("http://*****/IService);
rstr = null;
SecurityToken token = channel.Issue(rst, out rstr);

I have tried setting the WEB SSO time to two minutes, but it does not seem to have any affect.
What is the correct place to configure the expiration time on the ADFS?

A: You can use the ADFS PowerShell extension module to perform this operation:
Use:
Set-AdfsRelyingPartyTrust –TargetName "Relying party name" –TokenLifeTime 5

to set expiration to 5 minutes.
Remember to load the ADFS PowerShell snap-in first, by running
Add-PSSnapin Microsoft.Adfs.PowerShell

Further documentation can be found here:
http://technet.microsoft.com/en-us/library/adfs2-powershell-basics%28v=ws.10%29.aspx
http://technet.microsoft.com/en-us/library/adfs2-help-using-windows-powershell%28v=ws.10%29.aspx


text: Q: What are the pros and cons attaching TDE enabled .mdf to SqlLocalDb? I am thinking to attach TDE-enabled .mdf files to SqlLocalDb. Before investing time in it, I want to know whether it is worth doing that? So need some helpful suggestions.


text:
Q: How to divide up 'supply' evenly among rows in a dataframe by rank in Python? Ex. if I have 'supply' of 10, how can I distribute this evenly in a dataframe so that each row gets 1 until the 'supply' is depleted? Each row must get 1 before the first ranked row can get another. Below is the output I'm looking to achieve.
data = [['1','2','10'],['2','2','10'],['3','2','10'],['4','1','10'],['5','1','10'],['6','1','10'],['7','1','10']]

df = pd.DataFrame(data,columns=['rank','allocation','supply'])

| rank | allocation | supply |
|:---- |:---------- |:------ |
| 1    |  2         | 10     |
| 2    |  2         | 10     |
| 3    |  2         | 10     |
| 4    |  1         | 10     |
| 5    |  1         | 10     |
| 6    |  1         | 10     |
| 7    |  1         | 10     |

A: A simple strategy would be to construct your supply column as a list accordingly and assign it to your dataframe like this:
df = pd.DataFrame(range(100)) # example
supply_num = 10
supply_col = ([1] * supply_num) + ([0] * (df.shape[0] - supply_num))
df['supply'] = supply_col
print(df)


text:
Q: Get image thumbnail from easy-thumbnails by image location I have an icon image in all apps:
/app_name/static/model_name/images/icon.png
which is adding to model list in admin interface. And I want to crop it using easy-thumbnails and custom template tags:
template.html:
{% load project_tags %}
{% load_icon model %}{{ model.name }}

project_tags.py
from easy_thumbnails.files import get_thumbnailer
class LoadIcon(template.Node):

    def __init__(self, model_obj):
        self.model_obj = Variable(model_obj)

    def render(self, context):
        return '' % get_thumbnailer('/static/'+model_name+'/images/icon.png')['model_icon'].url

settings.py
THUMBNAIL_ALIASES = {
    '': {
        'model_icon': {'size': (20, 20), 'crop': True},
    },
}

But I have an "SuspiciousOperation" error:
SuspiciousOperation at /admin/
Attempted access to '/polls/images/icon.png' denied.
Did I do something wrong ?

A: The path '/polls/images/icon.png' is indeed suspicious, but I cannot see in your code where it comes from. It is probably interpreted as an absolute path on your file system. Check where you construct this path and let it begin with something like settings.MEDIA_ROOT.

A: Easy thumbnail uses a Django storage backend which is restricted to the MEDIA directory. The best way to resolve the problem would be to write a custom storage backend.


text:
Q: How to test a haml partial with an early return? I've got a haml partial that should render only for certain people, so it has a - return unless at the opening line:
- return unless user.is_allowed_to_see_this?

stuff here for only them to see

Works great in the app, but when testing the view, the rspec render helper throws a no implicit conversion of nil into String when trying to render the partial rather than returning empty/nil. So to test that the partial is working the test needs to look like:
  it 'does not show to unallowed user' do
    user = users(:not_allowed)
    expect do
      render('the/haml_partial', user: user)
    end.to raise_error(TypeError)
  end

Which feels like it's testing the wrong thing? I feel like the expect should be something like
expect(rendered).to be_empty

I've been digging through the documentation for a while and haven't found anything that seems to work for this. Changing the - return unless... to - if... makes the render call return an empty string rather than an error.  And maybe that's the fix? But I'd like to find a way to keep the early return which I feel is easier to read the intent of as there's no possibility of an else to think about.


text:
Q: Best approach to populate a JSP dropdown with fixed/static list of values I have a fixed list of 20+ values to be populated in a dropdown. The set of values are always going to remain the same, no future scope of modifications, additions or deletions.
Listing each of them as  in JSP is making the page look cluttered.
Or is it better reading it as a comma-separated string from a properties file and then iterating to populate the dropdown.
Or any other suggestions?
What will be the best approach to populate such a dropdown in JSP?

A: Are you using a framework such as Struts or Spring MVC?
The general approach to do this is to declare and initalise the array in your class file and create getters and setters.
Then in your JSP iterate through the array and add options to your dropdown dynamically.
For example
Create array with predefined values
String[] myArray = {"option1", "option2", "option3"};

Create getters and setters
public String[] getMyArray() {
    return myArray;
}
public void setMyArray(String[] myArray) {
    this.myArray = myArray;
}

Then create select dropdown and iterate through your array, you can use Struts2 tags like this
<select>
    <s:iterator value="myArray">
        <option value="<s:property/>"><s:property/></option> <!-- This prints out current value of the iterator -->
    </s:iterator>
</select>

Google struts2 iterator for more examples


text:
Q: How to check if there is no instance of an
* with a title in a list? Desired Behaviour
I want an element to show if there is no instance of an
 with a title in a list.
Current Behaviour
The logic below is only working if there is a title on the first
 in the list.  I think I am possibly misunderstanding how find() works.
What I've Tried
The snippet below shows the current behaviour and a test of the same logic in another scenario where all
's are being referenced.

$(document).on("click", ".sibling_1", function() {
  // show green box if there is *not* an instance
  // of a title in any of the li's
  if (!$(this).siblings(".sibling_2").find("li").attr("title")) {
    $(".woot").show();
  }
});

$(document).on("click", ".test", function() {
  $(this).siblings(".sibling_2").find("li").css("background", "yellow");
});
.woot {
  width: 250px;
  height: 250px;
  display: none;
  background: green;
}

click me - the green box should not show

test to select all li's

hi

hi

hi

hi

hi

A: You can use jQuery has attribute selector. Change .sibling_1 click event to following.
$(document).on("click", ".sibling_1", function () {
    if ($(this).siblings(".sibling_2").find("li[title]").length == 0) {
        $(".woot").show();
    }
});

Full Code Snippet

$(document).on("click", ".sibling_1", function () {
    if ($(this).siblings(".sibling_2").find("li[title]").length == 0) {
        $(".woot").show();
    }
});

$(document).on("click", ".test", function() {
    $(this).siblings(".sibling_2").find("li").css("background", "yellow");
});
.woot {
  width: 250px;
  height: 250px;
  display: none;
  background: green;
}

click me - the green box should not show

test to select all li's

hi

hi

hi

hi

hi


text:
Q: Barycentric coordinates. Harmonic warping of a point relative to a concave polygon in C I'm trying to get an array of weights that represent the influence a polygon's vertices have on an arbitrary position inside of it. With which I can interpolate the vertices of a deformed version of the polygon and get the corresponding deformed position.
Mean Value and Harmonic warping:

It seems that Harmonic coordinates would do this? My mesh goal:

I don't have easy time reading math papers. I found this Mathlab article, but still not grasping how to process each sampled position relative to the polygon's vertices
Meshlab article
Thanks!

A: You could try to create a Delaunay triangulation of the polygon and then use Barycentric coordinates within each triangle. This mapping is well defined and continuous, but in most cases probably not smooth (i.e. the derivative is not continuous).


text:
Q: ¿Cómo activar las sugerencias de auto completado con un atajo de teclado en Visual Studio Code? Siempre que escribo código en Visual Studio Code, en cada palabra me sale una ventana pequeña sugiriendo un autocompletado (En la mayoría) y me gustaría saber si alguien sabe cómo configurar para que la ventana de autocompletado aparezca con un atajo de teclado y no de forma automatica. En el entorno de desarrollo Netbeans es así, con el atajo Control+espacio aparecen las sugerencias de autocompletado.

A: En el archivo de configuración settings.json coloca:
"editor.quickSuggestions.other": false

Esto va a desactivar las sugerencias. Por defecto puedes disparar el autocompletado presionando Ctrl + .. Puedes ver más opciones para personalización en la documentación oficial.


text:
Q: Compile error with Attoparsec Text Lazy I am new to haskell, and the code below
import Data.Attoparsec.Text.Lazy
import qualified Data.Text.Lazy as T

toEol :: Parser T.Text
toEol = takeTill isEndOfLine

produces the following error message:
Couldn't match type `Data.Text.Internal.Text' with `TL.Text'
Expected type: Parser TL.Text
Actual type: Parser Data.Text.Internal.Text
In the return type of a call of `takeTill'
In the expression: takeTill isEndOfLine
In an equation for `cell':
    cell = takeTill isEndOfLine

Where does the type Data.Text.Internal.Text come from?  Importing Data.Text instead of Data.Text.Lazy seems to solve the issue.


text:
Q: Ternary using pass keyword python I have a working conditional statement:
if True:
    pass
else:
    continue

that I would like to turn it into a ternary expression:
pass if True else continue

However, Python does not allow this. Can anyone help?
Thanks!

A: pass and continue are a statements, and cannot be used within ternary operator, since the operator expects expressions, not statements. Statements don't evaluate to values in Python.
Nevertheless, you can still shorten the condition you brought like this:
if False: continue

A: Ternary expression are used to compute values; neither pass nor continue are values.

A: Point 1: Are your sure your condition is right? Because if True will always be True and code will never go to else block.
Point 2: pass and continue are not expressions or values, but a action instead You can not use these is one line. Instead if you use, 3 if x else 4 <-- it will work


text:
Q: Calculate pair-wise ratios between columns          A    B     C     D    E     F
 [1,]  187  174   183   115  101   104
 [2,]  451  166   177   842  101   133
 [3,]  727  171   187 12803   98   134
 [4,] 1532  181   196   730   98   108
 [5,] 4139  188   214 20358  105   159
 [6,]  689  185   211  1633  110   162
 [7,] 1625  184   195  2283  109   114
 [8,]  771  181   190   904  105   110
 [9,]  950  177   190  1033  106   112
[10,]  703  180   191   463  106   110
[11,] 2052  178   188  2585  100   105
[12,] 1161  178   187  2874   99   110
[13,]  214  175   184   173   98   110
[14,]  473  184   191   971  104   111
[15,]  756  185   193 14743  107   114

I have a dataset similar to the above data.
How can I produce a matrix with all the ratios calculated from the numbers between the next and the previous columns?
       B/A      C/B       D/C      E/D      F/E
 [1,]  174/187  183/174   115/183  101/115  104/101
 [2,]
 [3,]
 [4,]
 [5,]
 [6,]
 ...

A: From ping's suggestion, but adjusted for data frame column subsetting (meaning all I did was take off the commas).
new <- df[-1] / df[-length(df)]
colnames(new) <- paste(names(df)[-1], names(df)[-length(df)], sep = "/")
head(new)
#           B/A      C/B        D/C         E/D      F/E
# 1  0.93048128 1.051724  0.6284153 0.878260870 1.029703
# 2  0.36807095 1.066265  4.7570621 0.119952494 1.316832
# 3  0.23521320 1.093567 68.4652406 0.007654456 1.367347
# 4  0.11814621 1.082873  3.7244898 0.134246575 1.102041
# 5  0.04542160 1.138298 95.1308411 0.005157678 1.514286
# 6  0.26850508 1.140541  7.7393365 0.067360686 1.472727

If you possibly want to apply more than one function over the data, you can also do
Fun <- function(...) list(...)
Fun(`/`)[[1]](df[-1], df[-length(df)])


text:
Q: Error iterating through a Pandas series When I get the first and second elements of this series, it works OK, but from element 3 onwards, giving an error when I try to fetch.
type(X_test_raw)
Out[51]: pandas.core.series.Series

len(X_test_raw)
Out[52]: 1393

X_test_raw[0]
Out[45]: 'Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...'

X_test_raw[1]
Out[46]: 'Ok lar... Joking wif u oni...'

X_test_raw[2]

KeyError: 2

A: consider the series X_test_raw
X_test_raw = pd.Series(
    ['Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...',
     'Ok lar... Joking wif u oni...',
     'PLEASE DON\'T FAIL'
    ], [0, 1, 3])

X_test_raw doesn't have an index of 2 which you are trying to reference with X_test_raw[2].
Instead use iloc
X_test_raw.iloc[2]

"PLEASE DON'T FAIL"

You can iterate through the series with iteritems
for index_val, series_val in X_test_raw.iteritems():
    print series_val

Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...
Ok lar... Joking wif u oni...
PLEASE DON'T FAIL

A: There is no index with value 2.
Sample:
X_test_raw = pd.Series([4,8,9], index=[0,4,5])

print (X_test_raw)
0    4
4    8
5    9
dtype: int64

#print (X_test_raw[2])
#KeyError: 2

If need third value use iloc:
print (X_test_raw.iloc[2])
9

If need iterating only values:
for x in X_test_raw:
    print (x)
4
8
9

If need indexes and values use Series.iteritems:
for idx, x in X_test_raw.iteritems():
    print (idx, x)
0 4
4 8
5 9


text:
Q: What is this red warning I'm seeing on Google Play Console? I'm seeing a red warning in Google Play Console, in "Publishing Overview"

But I did complete "Data safety" form (some weeks ago)

What is this about?

A: check this and follow the instruction carefully.


text:
Q: terraform throwing "invalid or unknown key: zones" when creating azure vm i am using a key called "zones" while creating an azure vm using the resource "azurerm_virtual_machine". I am using terraform version 0.11.13.
According to the docs, "zones" key is allowed.
https://www.terraform.io/docs/providers/azurerm/r/virtual_machine.html
But when i run "terraform plan", i see the following error:
Error: azurerm_virtual_machine.testVM[4]: : invalid or unknown key: zones
Verified if i am using the key "zones" for the correct resource type and it looks okay according to hashicorp  docs
resource "azurerm_virtual_machine" "testVM" {
  <code to create VM>
  zones                         = ["1"]
}

A: you need to update your azurerm provider to the latest version. this is not something terraform handles directly, resource provider does that. I think you could do that by deleting the "internal" tf folder and running tf init.


text:
Q: Minifying bootstrap.js with connect-assetmanager causes syntax error. Why? Using connect-assetmanager in a node.js/Express app.
This works:
  js: {
      dataType: 'javascript',
      path: __dirname + '/../public/javascript/',
      files: [//'jquery-1.7.1.js'
             'bootstrap.min.js'
      ],
      route: /\/static\/javascript\/script\.js/
  }

(Note using the already minimized version of boostrap.js, and commented out the jquery file for testing).
This fails:
  js: {
      dataType: 'javascript',
      path: __dirname + '/../public/javascript/',
      files: [//'jquery-1.7.1.js'
             'bootstrap.js'
      ],
      route: /\/static\/javascript\/script\.js/
  }

Note the non-minimized bootstrap.js.
The failure is in the browser (Chrome).  At line 120 in the connect-assetmanager compressed portion of bootstrap.js there's a syntax error:
119 isActive=$parent.hasClass('open')
120 clearMenus()!isActive&&$parent.toggleClass('open')
  Uncaught SyntaxError: Unexpected identifier
121 return false}}

This is my first go at using something like connect-assetmanager to minify/concat static files.  Is this kind of thing typical with JS minifiers?  What do I do about this?
It's doubtful we will need to really debug into bootstrap.js on the client outside of prod anytime soon, but I don't want to invest in connect-assetmanager if corruption of Javascript is typical.

A: Not sure if this really counts as an answer, but the newer versions of the Bootstrap fix this issue.

A: You missed out the whole discussion on the missing semicolon issue with the bootstrap
https://github.com/twitter/bootstrap/issues/3057


text:
Q: Derivative of Riemann integral [of  a distribution function]. I am having a trouble solving a derivative of a Riemann integral while trying to obtain a distribution of a variable being a function of another random variable.
Let $ X $ be a random variable with density function $ f_X $ and $ Y = g(X) = aX+b $.
The calculations up to the point of confusion:
$ P( Y \leq y ) = P( aX+b \leq y ) $  which makes:
$ P(X \leq (y-b)/a ) $ for $ a > 0 $
$ 1 - P(X \leq (y-b)/a ) $ for $ a < 0 $
We have a general rule:
$ \displaystyle\int_{a(x)}^{b(x)} f(y,x)\,\mathrm{d}x = b^\prime(x) f( b(x), x ) - a^\prime(x) f( a(x), x ) + \displaystyle\int_{a(x)}^{b(x)} f_x^\prime(y,x)\,\mathrm{d}t $
Which in our case resolves to:
$ f( a(x), x ) = 0 $ since $ a(x) = -\infty $
$ - a^\prime(x) f( b(x), x ) = |a|^{-1} f_X( (y-b)/a ) $
But what does $ \displaystyle\int_{a(x)}^{b(x)} f_x^\prime(y,x)\,\mathrm{d}t $ account for? It seems from my answer sheet that the whole expression equals to $|a|^{-1} f_X( (y-b)/a )$, but I do not understand why.


text:
Q: Nohup background process with lots of output I have an app the runs in the background via nohup, and it can optionally output debugging information. When I nohup it in debug mode, it runs for only about 12 hours before it dies. The debugging info comprises about 3 or 4 lines per second. Auditd is logging a signal 11. The app runs for at least 24 hours interactively with no problem.
Obviously, I won't run it in debug mode in production.
So I'm curious what is causing it to stop.
Thanks.


text:
Q: how to change custom font for the list items How to change the font of the ListView items? Here I want to change the font to helvetica regular font. My TextView is assigned to the string variable. Please help me. Thank you in advance.
lv.setOnItemClickListener(newandroid.widget.AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick (AdapterView < ? > arg0, View view,int arg2, long arg3){

        String countryname = ((TextView) view.findViewById(R.id.countryname)).getText().toString();//this is the textview id assigned to the string variable//
        String coutrylist = "Algeria:DZ:213:49,Adrar;27,Ain Defla;43,Ain Temouchent"// these are the some of the list items in the list view//
        String split[] = coutrylist.split("\\$");
        // creating new HashMap
        String cid = "";
        String ccode = "";

        for (int i = 0; i < split.length; i++) {
            if (split[i].startsWith(countryname)) {
                String split3[] = split[i].split("\\:");
                cid = split3[2];
                ccode = split3[1];
            }
        }
        // On selecting single track get song information
        Intent i = new Intent(getApplicationContext(), Npanxx.class);
        //Toast.makeText(getApplicationContext(), "seleceted : " + countryname, Toast.LENGTH_SHORT).show();
        i.putExtra("country", countryname);
        i.putExtra("code", ccode);
        i.putExtra("id", cid);
        startActivity(i);
    }
});

A: Guessing you are using studio. Paste your font in src/main/assets/fonts/helveticaregular.ttf. And use this code to set the typface.
 Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/helveticaregular.ttf");
            txtView.setTypeface(myTypeface);

But I think you put here the wrong part of code. Probably you want this in your listview adapter.
Edit
You'll need to override the SimpleAdapter's getView(int position, View convertView, ViewGroup parent) method and cast the result to a TextView.
From there, setting a typeface works as usual.
Snippet, to be placed inside an (anonymous) extension of SimpleAdapter:
Typeface mTypeface = Typeface.createFromAsset(getAssets(), "fonts/helveticaregular.ttf"); // only needs to be initialised once.

@Override public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    TextView countryname = ((TextView)view.findViewById(R.id.countryname));
    countryname.setTypeface(mTypeface);
    return view;
}

A: First download the .ttf file of the font you need (helvetica.ttf). Place it in the assets folder(Inside assest folder create new folder named "fonts" and place it inside it). Now use following piece of code below TextView initialization.
Typeface myFont = Typeface.createFromAsset(getAssets(),"fonts/helvetica.ttf");
countryname.setTypeface(myFont);

A: Use Custom adapter for listview in custom adapter through findViewById method of View and the setTypeface method of TextView like below!
public View getView(int position, View convertView, ViewGroup parent)

{

View view = super.getView(position, convertView, parent);

 TextView countryname = ((TextView)view.findViewById(R.id.countryname));

 //put some custom font in your assets directory
 countryname.setTypeface(Typeface.createFromAsset
    (view.getContext().getAssets(),"yourfonttype.otf"));// you can also use
                                                        your context instead
                                                        of view.getContext()
                                                        that was asign from
                                                         activity

return view;
}


text:
Q: Checkout latest version of a file How can I checkout the latest version of a particular file from the remote branch?

A: First make sure get the latest version, type git fetch.
Then you can use git checkout origin/master <file_name>. (Assume you want the file in master branch)

A: Checkout the latest committed version of a file, locally:
git checkout file.txt

Or if you need the latest remote version of a file. I believe this fetches all remote branches, but you'll be on master locally.
git checkout master
git fetch

See all versions of file.txt:
git log --oneline --branches file.txt

The latest version of file.txt could be on a branch besides master. Since git log file.txt only searches the current branch, I added --branches. If the latest version was on another branch, then checkout that branch. Or checkout the id of the individual commit you want, like git checkout f823772.
With git log you can also specifiy --remotes=somewhere which might be helpful too.


text:
Q: How to apply boldface or header formatting to a sentence with LaTeX expression inside? So I'm trying to write up a document in Rstudio, and I have many sentences with in-line LaTeX expressions.  Some of these sentences, I want to either boldface entirely, or make them into document headers.  When I do this, I can only get the normal text to format into boldface, but the LaTeX does not change (it renders, but does not boldface along with the normal text).
A second, but related question--if I want to create ordered lists, or just indent a line with a LaTeX expression and have it in boldface, is it possible to do this?
For example:
**(a) Prove that $E(b_R) = \beta_1 + P\beta_2$.**

###(a) Prove that $E(b_R) = \beta_1 + P\beta_2$.

In both examples, the text "Prove that" correctly goes bold, but the rest does not.  Any advice on the easiest way to get the whole sentence into a consistent look?
For the second case, suppose I want to indent the line and/or I want to have two lines, with the second being part of a list connected to the first.  Is is possible to boldface either of these cases for the entire line, including the LaTex expression.
For the second case:
**(a) How to indent this line, and boldface everything: Prove that $E(b_R) = \beta_1 + P\beta_2$.**

***(a) How can I make this an un-ordered list, all boldface: Prove that $E(b_R) = \beta_1 + P\beta_2$.**
    **+(a) Can this line be a subpoint to the first, in all boldface? Prove that $E(b_R) = \beta_1 + P\beta_2$.**

Thanks for any tips.

A: You can add some code that automatically switches on \boldmath once \bfseries is used, c.f. https://tex.stackexchange.com/a/124311/140850:
---
output: pdf_document
---

\makeatletter
\g@addto@macro\bfseries{\boldmath}
\makeatother

**(a) Prove that $E(b_R) = \beta_1 + P\beta_2$.**

### (a) Prove that $E(b_R) = \beta_1 + P\beta_2$.

**(a) How to indent this line, and boldface everything: Prove that $E(b_R) = \beta_1 + P\beta_2$.**

***(a) How can I make this an un-ordered list, all boldface: Prove that $E(b_R) = \beta_1 + P\beta_2$.**
    **+(a) Can this line be a subpoint to the first, in all boldface? Prove that $E(b_R) = \beta_1 + P\beta_2$.**

Output:

Of course it would be better to add that code to some tex file that is included.


text:
Q: for loop with double condition I'm looking for a loop construct like for i in list where i < n. I would like to replace this mess:
for i in list:
    if i < n:
        #logic here

Is there something more compact and more elegant?

A: I'd write it with a guard condition to avoid the layer of indentation.
for i in list:
    if i >= n: continue

A one-liner is this:
for i in (k for k in list if k < n):
    ...

But I think the obvious code with the if inside the loop is much easier to understand.

A: You can use itertools.ifilter as follows:
>>> import itertools
>>> inlist = [1,2,3,4,5,6,7]
>>> for i in itertools.ifilter(lambda x: x < 5,inlist):
...     print i
1
2
3
4

If you want the reverse condition, e.g. greater than:
>>> inlist = [1,2,3,4,5,6,7]
>>> for i in itertools.ifilter(lambda x: x > 5, inlist):
...     print i
...
6
7

A: Short answer: No.
Long answer:
You could of course do this:
for i in (a for a in lst if a < n):
    # logic

But obviously that's a lot messier than your solution.

A: for i in [x for x in list if x<n]:
    pass

A: In python for this kind of things you have to use while, the for loop is iterating the list you just gave it.

A: It seems that itertools.takewhile would do what you want.
From the mothership:
itertools.takewhile(predicate, iterable)
Make an iterator that returns elements from the iterable as long as the predicate is true. Equivalent to:
def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
    for x in iterable:
        if predicate(x):
            yield x
        else:
            break

EDIT !ignore me! as Karl says ifilter(...) is the correct solution.
takewhile is only useful as they say on the mothership:

Make an iterator that returns elements from the iterable as long as the predicate is true.

I'd change that to be

Make an iterator that returns elements from the iterable only as long as the predicate is true.

As Buffy would say:

My bad.


text:
Q: How improve the performance of the query
I think the correct answer is B and C. My reasoning:
The returned row is 1, but the Disk IO and Query is very high. So optimizer use a full table scan not index scan. B and C can make query choose index scan.
But the provided answer is A and E. Why, is there valid reasoning for A and E? Are my answers and understanding correct? Or something else?

A: A - Makes no sense. employee_id is unique, the query retrieves at most 1 row based on an equality filter, this should be a dead simple INDEX UNIQUE SCAN.
B - I don't think so. employee_id is unique, the number of distinct values equals to the number of rows. With huge gaps in a unique column, a height balanced histogram can still provide extra information for better estimates for a full/range scan, but this is an index unique scan.
C - Maybe, but very unlikely in a real scenario. The above query should return its result after a few block reads and gets (lets say, <10, index height + 1 table access). Instead, it took 453 disk reads and 797 gets. Maybe the query read the whole table instead of an index unique scan. In that case, decreasing MBRC would increase the cost of a FTS maybe up to the point, where the index scan becomes favored. Still, in a real scenario, with proper statistics, I doubt this would happen.
D - Maybe, but again, unlikely in a real scenario. "Decreasing" the index may reduce the cost of it. The clustering factor and number of leaf blocks do not affect the cost of an index unique scan. This leaves us with the index height, and yes, that may decrease, which means the cost decreases as well, but this difference is so small, I find it difficult to believe the database would choose a FTS with 453 reads over an index unique scan with an index that has a much lower BLEVEL (typically between 0..3, it is rare to have indexes with higher BLEVEL).
E - Makes no sense. Same as A.


text:
Q: Why under specific enviroments UNICODE characters trigger an EncodeError and at others not? I am making a Python project that needs to work with Greek characters print, edit and return strings.
On my main PC that has the Greek language installed everything runs fine but when I am running on my English laptop the same program with the same version of python an encode error is triggered. Especially this one:

EncodeError: 'ascii' codec can't encode characters in position 0-2:
  ordinal not                         in range(128)

The error happens due to this code
my_string = "Δίας"
print(my_string)

Why is this happening and what I need to do to fix it?

A: Why is this happening? You are using Python 2 and although it supports Unicode, it makes you jump through a few more hoops explicitly than Python 3 does. The string you provide contains characters that fall outside the normal first 128 ASCII characters, which is what is causing the problem.
The print statement tries to encode the string as standard ascii, but it runs into characters it doesn't understand and by that point, it does not know what encoding the characters are supposed to be in. You might think this is obvious: "the same encoding the file is in!" or "always UTF-8!", but Python 2 wants you to make it explicit.
What do you need to do to fix it? One solution would be to use Python 3 and not worry about it, if all you need is a quick solution. Python 3 really is the way forward at this point and using Python 2 makes you solve problems that many Python programmers today don't have to solve (although they should be able to, in the end).
If you want to keep using Python 2, you should change your code to this:
# coding=utf-8
my_string = u"Δίας"
print(my_string.encode('utf-8'))

The first line tells the interpreter explicitly what encoding the source file was written in. This helps your IDE as well, to make sure it is showing you the code correctly. The second line has the u in front of the string, telling Python my_string is in fact a unicode string. And the third line explicitly tells Python that you want the output to be utf-8 encoded as well.
A more complete explanation of all this is here https://docs.python.org/2/howto/unicode.html
If you're wondering why it works on your Greek computer, but not on your English computer - the default encoding on the Greek computer actually has the code points for the characters you're using, while the English encoding does not. This indicates that Python is clever enough to figure out that things are utf (and the string is a series of unicode code points), but by the time it needs to encode them, it doesn't know what encoding to use, as the standard (English) encoding doesn't have the characters in the string.


text:
Q: Removing cuda-repo Network Installer and installing the local version I have followed the instructions in a tutorial to install cuda on Ubuntu 14.04. Problem is that I didn't notice that I installed the Network Version of the cuda-repo*.deb . How can I change this and install the local version instead of the network one?

A: *

*Remove the Network Installer version

*

*with with conf files
sudo dpkg --purge cuda-repo-ubuntu1404

*without conf files
sudo dpkg --remove cuda-repo-ubuntu1404

*Install the Local Package Installer version with
sudo dpkg --install cuda-repo-ubuntu1404-7-0-local_7.0-28_amd64.deb


text:
Q: Java - How to read a CSV file into a Map> Input (CSV File)
Header1,Header2,Header3
Data1,Data2,Data3
Data4,Data5,Data6
Data7,,
,,Data8
I am trying to parse through a CSV file similar to the above structure and store the data into a Map<String (Row Number), Map<String (Column Header), String (Column Value)>>.

A: Assuming your file is well formed and each row has the same column count as your header, something like below migght be a starting point:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public final class Example {

    public static void main(String[] args) throws IOException {

        //create a map
        Map<String, Map<String, String>> map = new LinkedHashMap<>();

        Path filePath = Paths.get("path to your/test.csv");
        Charset charset = StandardCharsets.UTF_8;

        //read the file
        List<String> fileContent = Files.readAllLines(filePath, charset);

        // get the header
        String[] header = fileContent.get(0).split(",");

        AtomicInteger lineNumber = new AtomicInteger(1);

        //fill the map
        fileContent.stream()
                   .skip(1)
                   .forEach(line -> map.put(
                           String.valueOf(lineNumber.getAndIncrement()),
                           getRowData(header, line.split(","))));

        System.out.println(map);
    }

    // helper method to make the filling of the map in the stream readable
    private static Map<String, String> getRowData(final String[] header, final String[] line) {
        return IntStream.range(0, header.length)
                        .mapToObj(i -> Map.entry(header[i], line[i]))
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }
}


text:
Q: Using WinSCP .NET assembly on Linux I have deployed my application based on WinSCP .NET assembly in Linux.
I'm getting this error:

WinSCP.SessionLocalException: The winscp.exe executable was not found at the location of the assembly WinSCPnet

SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Sftp,
    HostName = _sftpConfig["Host"],
    UserName = _sftpConfig["UserName"],
    Password = _sftpConfig["Password"],
};

A: WinSCP .NET assembly is a wrapper around WinSCP.exe scripting interface.
WinSCP is a Windows application. It does not run on Linux on its own. Consequently, the assembly is not really intended to be used on Linux. Quoting WinSCP .NET assembly documentation:

The library is primarily intended for advanced automation tasks on Microsoft Windows that require conditional processing, loops or other control structures for which the basic scripting interface is too limited.

On the other hand, standalone WinSCP works under Linux using Wine without any problem. And there's .NET Core build of the .NET assembly. So it is quite likely that it is possible, but I haven't seen it done yet.


text:
Q: JOCL eventCallback not called until another kernel starts I'm trying to run a multithreaded Java application that executes OpenCL kernels. I wanted to notify one of the threads when a Kernel finishes, so I tried to use the clSetEventCallback method.
For that I prepared a method
void runKernel(
    cl_program program,
    String functionName,
    Object... params,
    long[] globalWorkSize,
    long[] localWorkSize
){
    System.out.println(System.currentTimeMillis() +": Preparing Kernel "+kernel+);
    int[] errCode = new int[1];
    int errno;
    cl_kernel kernel = CL.clCreateKernel(program, functionName, errCode);

    /******INSERT ALL THE PARAMS******/

    System.out.println(System.currentTimeMillis() +": Enqueueing Kernel "+kernel+);

    cl_event event = new cl_event();
    CL.clEnqueueNDRangeKernel(this.queue, kernel, 1, null, globalWorkSize, localWorkSize, 0, null, event);
    CL.clSetEventCallback(event, CL_COMPLETE, new EventCallbackFunction() {
        @Override
        public void function(cl_event event, int command_exec_callback_type, Object user_data) {
            System.out.println(System.currentTimeMillis() +": Finished kernel " + user_data);
        }
    }, kernel);
}

I call this function to execute three different kernels with a 5 secongs gap inbetween. The code runs fine and I get the expected result. However, when I look at the application output, the callback methods are not executed upon the actual kernel completion but once the program calls again the run method. The callback for the last executed kernel is never executed (the kernel is executed since the results obtained are correct).
1475085785924: Prepared Kernel cl_kernel[0x7f8b28098c90]
1475085785924: Enqueueing Kernel cl_kernel[0x7f8b28098c90]
1475085790925: Prepared Kernel cl_kernel[0x7f8b284fbd50]
1475085790925: Enqueueing Kernel cl_kernel[0x7f8b284fbd50]
1475085790925: Finished kernel cl_kernel[0x7f8b28098c90]
1475085795926: Prepared Kernel cl_kernel[0x7f8b2851abd0]
1475085795926: Enqueueing Kernel cl_kernel[0x7f8b2851abd0]
1475085795926: Finished kernel cl_kernel[0x7f8b284fbd50]

Is there any problem on my code so the callbacks are not executed until the next kernel is enqueued? Did I miss something? Or the JOCL/OpenCL library is not notifying a kernel end properly?

A: Apparently, there is a bug on the OpenCL implementation that I use.
As a workaround, I'm enqueueing a kernel that does nothing after enqueueing the actual kernel.
I have a cl_program attribute with an empty program.
private cl_program doNothing;

int[] errCode = new int[1];
String blankCode = "__kernel void blank(){}";
doNothing = CL.clCreateProgramWithSource(context, 1, new String[]{blankCode}, new long[]{blankCode.length()}, errCode);
CL.clBuildProgram(doNothing, 1, new cl_device_id[]{deviceId}, null, null, errCode);

And after enqueueing the kernel execution I call the following method that enqueues the blank kernel
private void addBlankKernel() {
    int[] errCode = new int[1];
    cl_kernel kernel = CL.clCreateKernel(this.doNothing, "blank", errCode);
    CL.clEnqueueNDRangeKernel(this.queue, kernel, 1, null, new long[]{1}, new long[]{1}, 0, null, null);
}


text:
Q: how to apply a multiplier on a dataframe based on conditions? Given this first dataframe df_1:
df_1 = pd.DataFrame({'id':[1,2,1,3,1],
                     'symbol':['A','B','C','A','A'],
                     'date':['2021-02-12','2021-02-09','2021-02-14','2021-02-02','2021-02-05'],
                     'value':[1,1,1,1,1]})

   id symbol        date  value
0   1      A  2021-02-12      1
1   2      B  2021-02-09      1
2   1      C  2021-02-14      1
3   3      A  2021-02-02      1
4   1      A  2021-02-05      1

And given this second df_2:
df_2 = pd.DataFrame({'id_symbol':['1_A', '1_A'],
                     'init_date':['2021-02-01','2021-02-01'],
                     'end_date':['2021-02-05', '2021-02-12'],
                     'multiplier':[5,2]})

I need to apply this df_2.multiplier on df_1 for rows on df_1.value where the concat of id and  _ and symbol is equals the df_2.id_symbol, and if the df_1.date is within the df_2.init_date and df_2.end_date.
My result should be like this, after the code:
   id symbol        date   value
0   1      A  2021-02-12       2
1   2      B  2021-02-09       1
2   1      C  2021-02-14       1
3   3      A  2021-02-02       1
4   1      A  2021-02-05      10

5 = 1 * 5 // 10 = 1 * 5 * 2
My both dataframes are quite bigger than this.

A: Since there's the possibility of multiplying the value more than once we will do a merge, find all possible matches and sum the multipliers to figure out how much we need to multiply the original row by.
First split the 'id_symbol' column and use datetime64 dtypes so we can do merges and comparisons:
import pandas as pd
import numpy as np

df_1['date'] = pd.to_datetime(df_1['date'])
df_2['init_date'] = pd.to_datetime(df_2['init_date'])
df_2['end_date'] = pd.to_datetime(df_2['end_date'])

df_2[['id', 'symbol']] = df_2['id_symbol'].str.split('_', expand=True)
df_2['id'] = df_2['id'].astype('int64')

Now merge on all possible multipliers, but set it to 1 if it's outside of the date range. Determine the total multiplier for that row (i.e. product of all multipliers that satisfy the date condition) and use that to multiply the with the original DataFrame (aligns on df_1's Index).
mult = df_1.reset_index().merge(df_2, on=['id', 'symbol'], how='left')
mult['multiplier'] = np.where(mult.date.between(mult.init_date, mult.end_date),
                              mult.multiplier, 1)
mult = mult.groupby('index')['multiplier'].prod()
#index
#0     2.0
#1     1.0
#2     1.0
#3     1.0
#4    10.0
#Name: multiplier, dtype: float64

df_1['value'] = df_1['value']*mult

print(df1)
   id symbol       date  value
0   1      A 2021-02-12    2.0
1   2      B 2021-02-09    1.0
2   1      C 2021-02-14    1.0
3   3      A 2021-02-02    1.0
4   1      A 2021-02-05   10.0

A: I was able to get to your desired outcome with the following process. I will comment on the code to explain each step, but it is fairly simple:
# Our imports
import pandas as pd
import numpy as np

# Create the id_symbol column in df_1 and perform a left merge
df_1['id_symbol']=df_1['id'].astype(str)+"_"+df_1['symbol'].astype(str)
df_1 = pd.merge(df_1,df_2,how='left',on='id_symbol')

# Make sure you convert to datetime, and handle the NaT succesfully
for i in ['init_date','end_date']:
    df_1[i] = pd.to_datetime(df_1[i],errors='coerce')

# Use np.where to check whether the conditions you want are satisfied
df_1['value'] = np.where((df_1['init_date'] <= df_1['date']) & (df_1['date']  <= df_1['end_date']),
                         df_1['value']*df_1['multiplier'],1)

# Drop the unwanted columns
df_1.drop(['id_symbol','init_date','end_date','multiplier'],axis=1,inplace=True)

Will get back your desired outcome:
   id symbol        date  value
0   1      A  2021-02-12    1.0
1   2      B  2021-02-09    1.0
2   1      C  2021-02-14    1.0
3   3      A  2021-02-02    1.0
4   1      A  2021-02-05    5.0

A bit of an ad-hoc, but seems to be working.


text:
Q: How to fix memory leak when using redux in useEffect? When moving pages through NavLink, most of the memory leak warnings disappeared when the cleanup function was used. However, when using react-redux, a memory leak warning occurs.
How do I create a cleanup function to get rid of this warning message?
My code is here. For this code, using useState instead of useDispatch made the warning go away.
function List() {
  const [isShow, setIsShow] = useState(false);
  const dispatch = useDispatch();
  const list = useSelector((state) => state.list);

  useEffect(() => {
    async function load() {
      await dispatch(loadlist());
      setIsShow(true);
    }
    let clean = true;
    setIsShow(false);
    if (clean) load();
    return () => (clean = false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (isShow) return <Table data={list} />;
  else return <Loading />;
}


text:
Q: D3 date range by hour; day repeats every 7 days So, I am working on a visualization that calculates the angle and distance of the sun at a specific location for each hour of every day in a year. The calculations take up about 550 lines of code, so I'll leave that code out. I'm using the D3 library to get the range of hours and relative day, month, and year of the range of dates. To get the range, I am using this line of code.
var hourRange = d3.time.hours(new Date(2013, 1, 1), new Date(2013, 12, 31));

After getting the calculations to work, I got very excited. Having 8736 objects holding the 9 values,
hourRange[i] = [hour, day, month, year, solar azimuth angle, solar elevation angle, EOT, solar declination angle, cosine of solar zenith angle]

... and finally starting the visualization process, I found that the day values went from 0-6, but instead of increasing until the end of the month, continued to repeat 0-6 until the end of the month and started the 0-6 value loop over again. Thinking this may be an issue from the calculations, I tried printing out the day value of the hour range directly and found the same issue happening. Reading the Time Interval API Reference for the D3 library, this seems to be an anomalous error.
Does anyone know why this is happening, as well as any solutions to get the range of hours and their relative dates without this issue of the day value repeating every week? Any insight to this will be greatly appreciated!
EDIT: To be clear. When type hourRange[500] in the console, it returns:
Date 2013-02-22T01:00:00.000Z

But, when I type hourRange[500].getDay() in the console, it returns:
4

when it should clearly be 22.

A: D3.time.getDay() returns the value of the day of the week. I needed to use D3.time.getDate() to get value of the day of the month.


text:
Q: Many browsers are needed but it takes too much memory Hi I am working on an application in which I need almost 10 webBrowsers which render when some button is clicked. Now this amount of browsers takes too much memory on RAM. Is there any way to reduce the memory consumption with the mentioned number of browsers?
Thanks

A: I doubt there is a lot you can do to reduce memory consumption depending on where the memory is being used.
It depends on what is taking the memory, you could try launching the browsers in No-addon mode which would save some memory, additionally if the memory consumption is increasing becuase of data in the pages stored in the ViewState of the page then moving data from the ViewState to the session would help with this.

A: As long as you make sure you dispose or reuse any WBCs - don't worry about it. 100 megs in the task manager is not worth worrying about.


text:
Q: Calling a method on an object I am new to C# and I am trying to write a roulett simulator. I am trying to simulate the real world where you have a wheel and a croupier and the croupier spins the wheel. In Object Oriented Programming that means calling a method on another object from a differnt object. Is the code below where I pass the wheel obect around the correct way in C# to do this?
Thanks in advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
        {
        static void Main(string[] args)
        {
            Wheel luckyWheel = new Wheel();
            Croupier niceLady = new Croupier();
            niceLady.SpinWheel(luckyWheel);
        }
    }

    class Wheel
    {

        public void Spin()
        {
            Console.WriteLine("Wheel Spun");
        }
    }

    class Croupier
    {
        public void SpinWheel(Wheel spinMe)
        {
            spinMe.Spin();
        }

    }
}

A: Yes it is correct and also good way to do the stuff, as your code becomes a testable.
As you have functionality in one class Wheel , executors of that functionality in others: Croupier , ...

A: Yes, it's correct for a start. I advise you separating the classes into different .cs files.

A: Yes this is the right way to do that, as your both classes are in the same assembly you can declare the method Spin() internal.

A: A better way to do it would be to pass the wheel to the courier when you create that class. The constructor would then store the wheel reference in a field, and then when you spin the wheel, the croupier can access the wheel via the local field.
Like so:
class Program
{
    static void Main(string[] args)
    {
        Wheel wheel = new Wheel();
        Croupier croupier = new Croupier(wheel);
        croupier.SpinWheel();
    }
}

class Wheel
{
    public void Spin()
    {
        Console.WriteLine("Wheel Spun");
    }
}

class Croupier
{
    private Wheel wheel;

    public Croupier(Wheel wheel)
    {
        this.wheel = wheel;
    }

    public void SpinWheel()
    {
        wheel.Spin();
    }
}

A: You can improve it as Adam K Dean stated which leads you to use the strategy pattern as explain by the dotFactory here.


text:
Q: Simple Z3 exercise returning unknown I'm starting using SMT solvers and I was practicing with this simple problem:
Exercise 5. Using Z3 at the restaurant:
(a) Encode the following menu choices into Z3 and determine what a customer could buy using exactly
$15.05
• Mixed fruit $2.15
• French Fries $2.75
• Side Salad $3.35
• Hot Wings $3.55
• Mozzarella Sticks $4:20
• Sampler Plate $5:80
(b) Is it possible to order everything on the menu?
(c) Does this problem have only one solution? If it does
 not, what are the other solutions?

My solution for a) is:
from z3 import *

fruit = Real('fruit')
fries = Real('fries')
salad = Real('salad')
wings = Real('wings')
mozzarella = Real('mozzarella')
sampler = Real('sampler')

Total= Real('total')

multiplier1= Int("mul1")
multiplier2= Int("mul2")
multiplier3= Int("mul3")
multiplier4= Int("mul4")
multiplier5= Int("mul5")
multiplier6= Int("mul6")

x = Real('x')
y = Real('y')
s = Solver()
s.add(multiplier1*fruit + multiplier2*fries + multiplier3*salad + multiplier4*wings + multiplier5*mozzarella + multiplier6*sampler == 15.05)

print(s.check())
print(s.model())

But it is returning unknown. Why??
Solution for b):
from z3 import *

fruit = Real('fruit')
fries = Real('fries')
salad = Real('salad')
wings = Real('wings')
mozzarella = Real('mozzarella')
sampler = Real('sampler')

Total= Real('total')

multiplier1= Int("mul1")
multiplier2= Int("mul2")
multiplier3= Int("mul3")
multiplier4= Int("mul4")
multiplier5= Int("mul5")
multiplier6= Int("mul6")

s = Solver()
s.add(multiplier1*fruit + multiplier2*fries + multiplier3*salad + multiplier4*wings + multiplier5*mozzarella + multiplier6*sampler == 15.05)
s.add(multiplier1>0)
s.add(multiplier2>0)
s.add(multiplier3>0)
s.add(multiplier4>0)
s.add(multiplier5>0)
s.add(multiplier6>0)

print(s.check())
print(s.model())

Same result! :(
Solution for c): I need to get the solutions first :'(
This is a very simple problem. What am I doing wrong?
NOTE: Exercise gotten from: http://www.loria.fr/~mery/malg/Z3.pdf
Thanks
SOLUTION:
from z3 import *

fruit = Real('fruit')
fries = Real('fries')
salad = Real('salad')
wings = Real('wings')
mozzarella = Real('mozzarella')
sampler = Real('sampler')

multiplier1= Int("mul1")
multiplier2= Int("mul2")
multiplier3= Int("mul3")
multiplier4= Int("mul4")
multiplier5= Int("mul5")
multiplier6= Int("mul6")

s = Solver()
s.add(multiplier1*fruit + multiplier2*fries + multiplier3*salad + multiplier4*wings + multiplier5*mozzarella + multiplier6*sampler == 15.05)
s.add(fruit==2.15)
s.add(fries==2.75)
s.add(salad==3.35)
s.add(wings==3.55)
s.add(mozzarella==4.20)
s.add(sampler==5.80)
s.add(multiplier1>=0)
s.add(multiplier2>=0)
s.add(multiplier3>=0)
s.add(multiplier4>=0)
s.add(multiplier5>=0)
s.add(multiplier6>=0)

while s.check() == sat:
  print s.model()
  s.add(Or(multiplier1 != s.model()[multiplier1], multiplier2 != s.model()[multiplier2] ,multiplier3 != s.model()[multiplier3] , multiplier4 != s.model()[multiplier4] ,multiplier5 != s.model()[multiplier5], multiplier6 != s.model()[multiplier6])) # prevent next model from using the same previous one

A: Make sure that you use the prices for each item. Notice that the price of fruit $2.15 does not appear in the formulas. Hope that is enough of a hint for you to fix these :-)
As to why the formula first formula returns unknown, notice that both formulas are non-linear mixed integer real queries. The formulas as stated are really easy to satisfy, but SMT solvers for QF_NIRA are not robust. You might want to read up on Hilbert's 10th problem for more historical context.


text:
Q: Is there in bash scripts a way of using variables to specify different bash arrays For example in this simple script
    #!/bin/bash

    declare -a MYARRAY1
    declare -a MYARRAY2

    function updatearray {
    ARRAY=$1
    VALUE=$2

    $ARRAY+=$VALUE

    }

    updatearray MYARRAY1  "yyyy "
    updatearray MYARRAY2  "bbbb "

    echo "${MYARRAY1[@]}"
    echo "${MYARRAY2[@]}"

    exit 0

Just results in "line 10: MYARRAY1+=yyyy: command not found" rather than updating the array.  This is actually for a more complex bash script I'm working on that has more arrays I want to update, so I'm hoping to avoid 'case' statements which would mean a big function body

A: You can use namerefs, but take care:
updatearray () {
    declare -n a=$1
    a+=$2
}


text:
Q: Managing Bitlocker encryption on C# I need to manage (short for "enable and then immediately disable") bitlocker encryption on removable drives.
Bitlocker is enforced by company policy, but in order to release to customers their USB installation drives I need to encrypt the drives, move the needed files into themand finally decrypt them. This takes a lot of time and is currently manually made, so I would love to automate the crypt/copy/decrypt part and integrate it into my C# solution.
I tried to write a Powershell scrip (disclaimer: I don't know how to script in PS) but I keep getting errors like this:
Enable-BitLocker : Impossibile risolvere il set di parametri utilizzando i parametri denominati specificati.
In C:\Projects\Selco.WeldNet.SinergyManager\Selco.Weldnet.SynergyManager.LicenseCreator\Script\ManageUSBDrive.ps1:49 car:2
+     Enable-BitLocker -MountPoint "$thisDriveletter" -EncryptionMethod ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Enable-BitLocker], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Enable-BitLocker

Aren't any api/library/nuget package for C# that could help managing bitlocker?


text:
Q: Transactional operation between multiple database How can I use transactional operation between multiple database with Entity framework core ((2.1))? (Distributed Transaction)
try
{

    using (var tranScope = new TransactionScope())
    {
        using (var ctx1 = new TestDBContext())
        using (var ctx2 = new TestDB2Context())
        {
            ctx1.Person.Add(new Person { Name = "piran" });

            ctx2.Course.Add(new Course { Name = "C#" });

            ctx1.SaveChanges();
            ctx2.SaveChanges();
        }

        tranScope.Complete();
    }

}
catch(Exception ex)
{
    Debug.WriteLine(ex.Message);
}

When running above code I give this exception:

This platform does not support distributed transactions


text:
Q: A mathematical integer range function I want a function f(x) that uses the constants a, b, M, N  and,
Always, a < b
If x < a then f(x) = M
If x > b then f(x) = N
Else, f(x) = x
(x, a, b, M, N  all are integers.)

Above image shows a plot created using paint app , where
 a=3, b=10, M=5, N=9
In words, it is a function that takes an integer. If it is on a certain range, it outputs the same integer.
Else, it outputs a pre chosen number according to whether the integer is larger or lower than the specified range.
What will be the equation to get that outputs?
(I want an equation of the function, there can be more than one)

A: Functions aren't magic and they don't need nor always have special names or formulas.  The function you want is:
$f (x)=M $ if $x>a $
$f (x)=N$ if $x <b$
$f (x)=x$ otherwise.
That's it.  That IS your function.  There is nothing more that needs to be said.

A: If you don't like to write down explicit cases (although there's nothing wrong with doing so), you can also use the Iverson bracket to write your function as
$$f(x) = M\,[x<a] + N\,[x>b] + x\,[a\le x\le b]$$


text:
Q: declaration of callback function and return type in the following function, for callback function start_routine, the return type is void **
 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
               void *(*start_routine) (void *), void *arg);

but when we define the callback function, it is like this:
void func(void *)

I know it is a function, but I thought at least the callback function should be like:
void* func(void *);

where I'm wrong? thanks!

A: void func(void *) is just a normal function which returns nothing and takes a void*. It cannot be placed as a function's argument.
void* func(void *) is similar to above, the only difference being that it returns a void* pointer.
A callback function looks like this return_type (*function_name)(arguments). Here, an example is void* (*start_routine)(void *). This is a valid function argument.
The pthread_create function takes as its second last argument a pointer to a function start_routine whose return type is void* and has only one argument of type void*.
An excerpt from this page: http://www.cprogramming.com/tutorial/function-pointers.html
Sometimes people get confused when more stars are thrown in:
void *(*foo)(int *);

Here, the key is to read inside-out; notice that the innermost element of the expression is *foo, and that otherwise it looks like a normal function declaration. *foo should refer to a function that returns a void* and takes an int*. Consequently, foo is a pointer to just such a function.


text:
Q: Windows defender thread using 100% CPU The problem is the following - a thread of windows defender hangs and consumes 100% of one core (viewed with process explorer). It happens only when there is InPrivate IE instance running. The result is that IE becomes completely unresponsive and the solution is to just kill the offending thread (not process) from process explorer. Then it returns to normal.
If the thread is not killed it will stay in that situation indefinitely.
What could cause such behaviour (also happens when php running under apache 2.2 tries to make file_get_contents - but I am not completely sure about that)

A: I have the same issue since the first MSE beta and MS ignores all feedback.
Here is what I see in Windows 8:

There is no way to fix it. Switch to a different AV tool.


text:
Q: How to make an image inside a chat bot iframe, enlarge or go full screen on click when you cannot add id's or images attribute to the src image url? I have a chat bot that I am working on that is using websdk and the images are added through a tool from Oracle which will not accept image attributes, you just put the image urls in the correct fields. However the images are resized to the tiny chatbot iframe and I would like to figure out how to enlarge them on click or hover. Outside of the tool I can apply Javascript and CSS, I just cant edit the HTML as far as I can tell because it's rendered by the tool.
Here is what the tool looks like, see how its not using HTML, you just input the links?
Oracle Tool
I used hover CSS and that words to enlarge the images but the image is still stuck inside the iframe sized so its not a real solution.
.oda-chat-card-image:hover {
  -ms-transform: scale(1.5); /* IE 9 */
  -webkit-transform: scale(2); /* Safari 3-8 */
  transform: scale(2);

Hover Example
I found some code that puts the image into a target div which is the whole background iframe. I use this iframe to open links in the background of the chat bit that the bot suggests so the used stays in the same window. Which I like, but it requires the images have inline attributes that I cannot add.
I thought if I could use some Javascript to add the attributes to all images that I could get what I want but that seems to require adding unique IDs to the images but that is something I cannot do. I wondered what other possibilities anyone else could suggest.
The images do have a class so perhaps I can access them that way somehow. That's how I was able to apply the hover CSS class=oda-chat-card-image
This is the code I tried to use for opening the image on click in the background iframe which I named name="mainPageIframe" id="mainPageIframe"
const change = src => {
    document.getElementById('mainPageIframe').src = src

If I inspect the image in the browser and manually add
onclick="change(this.src)"

to the end of an image,
Example code rendered by the chatbot tool but edited where I added the onclick attribute manually while in f12 inspecting the image.

Example of adding the attribute manually to produce the result I want
then when I click the image it opens in the background iframe. Doing this is the best thing I could think of but I would rather have the image open as an enlarged overlay over the whole screen instead of trapped inside the iframe. That's why I thought copying it to the main page iframe would be a solution. Any ideas on how I can apply
onclick="change(this.src)"

to all images in my webpage without unique id's or perhaps apply a different solution all together?
This is the HTML file I am working on that I can edit. It calls the bot contents by the URI and channelID. I am able to apply CSS to the items in the bot and Javascript, I just don't know how to get the images in the bnot to pop up or out side of the chatbot iframe and enlarge.
 <!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <title>ODA Live Chat Example</title>

            Your browser doesn't support iframes


text:
Q: Combining multiple string replace into one statement? This is what I'm doing now:
text = text.replace(/{{contact first}}/gi, contact.first)
    .replace(/{{contact last}}/gi, contact.last)
    .replace(/{{contact name}}/gi, contact.first + ' ' + contact.last);

Is there a way of doing:
text = text.replace([
    /{{contact first}}/gi,
    /{{contact last}}/gi,
    /{{contact name}}/gi
], [
    contact.first,
    contact.last,
    contact.first + ' ' + contact.last
]);

A: var contact={first:'John',last:'Doe'}

var text='{{contact first}} blah blah {{contact last}} blah blah blah {{contact name}} blahblah';

text= text.replace(/{{contact (first|last|name)}}/gi, function(a, b){
    return contact[b]|| contact.first+' '+contact.last;
});

text;

/*  returned value: (String)
John blah blah Doe blah blah blah John Doe blahblah
*/

A: That is not supported in Javascript but you can probably use String#replace like this:
text = text.replace(/{{contact (first|last|name)}}/gi, function($0, $1) {
    if ($1 == "last")
       return contact.last;
    else
       return contact.first;
});


text:
Q: htaccess removing index.php only root folder Matured one question which I can not handle himself and is forced to ask for help.
So...
I have configured .htaccess file:
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]

This code removes all directories index.php on site. I also need to remove it only in the site root. The problem is that the root can be any subdirectory as "/" and "/some_folder/"
Is it possible to do this without explicit basedir?
For example for CNC I managed to make it so:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . ./ [L]

Thus, the problem:
Site root = httр://site.com/sub/
Remove index.php need only in the root directory.
Rot directory may vary and the decision should be without explicit basedir

A: You can use this rule to remove index.php from root only:
RewriteCond %{THE_REQUEST} \s/index\.php [NC]
RewriteRule ^index\.php$ / [L,R=301,NC]


text:
Q: Is this correct wording?

The Point $A$ inside soccer field is closer to $x$ axis than to $y$
axis. Given that the coordinate of $A$ is given by
$A(\log_2(17-x),3)$, determine the sum of the integer values of $x$.

The question comes down to solving,
$$
8>17-x \implies x>9
$$
At this point, many people take the sum of $10+11+12+13+14+15+16$, and arrive at $81$. It turns out that this is wrong because the question says the point is inside the field, but $\log1=0$ and that makes it on the $x$ axis.
(1) Do you think this is clear? (For one thing, in the rules of soccer, the line itself is considered inside the field.)
(2) Obviously, the question setters did not want to draw attention to the "inside the field" part, such as making it bold or underlining it. If you think that the current form is not clear, how would you put it, making it both clear but without drawing attention to it? (For example, not something like: The axes are not considered inside the field.)


text:
Q: Bind xaml vector images dynamically I'm looking for a way to bind xaml images dynamically in code.
There are lots of examples online to show how to bind png or xaml images in the window's xaml, or to load png files in code.
But I have found no examples for xaml files with build action=page. XmlReader can't handle them since they are compiled to baml.
LoadComponent(new Uri("...filename.baml") will apparently load the baml but what kind of image class do I load this into?  BitmapImage(new Uri("...filename.baml") does not seem to work, probably because it's not a bitmap.
Thanks in advance.

A: Additionally, if your image is stored in a Xaml vector file in this kind of format:

You can load the individual xaml vector images in the following way (it is probably best to prevent the dictionary being added multiple times, if like me, you are loading it via an OpenFileDialog):
C#:
string fullPathAndFileName = "C:\Image_Name.xaml";
ResourceDictionary dict = new ResourceDictionary();
dict.Source = new Uri(fullPathAndFileName);
Application.Current.Resources.MergedDictionaries.Add(dict);
DrawingImage image = dict[dict.Keys.Cast().ToList()[0]] as DrawingImage;
myImage.Source = image;
Xml:
Image Height="200" Width="200" x:Name="myImage"

A: After much trial and error and searching, the following article helped me on my way:
Access ResourceDictionary items programmatically
If each Xaml vector image is contained inside a ResourceDictionary with a key (see my 2nd post below for the format)...
If your Xaml vector image files are all stored in your project (build action: page), you can load them in the following way:
//Get the ResourceDictionary using the xaml filename:
ResourceDictionary dict = System.Windows.Application.LoadComponent(new Uri("/yourprojectname;component/youriconfolder/youriconfilename.xaml", System.UriKind.Relative)) as ResourceDictionary;

//Get the xaml as a DrawingImage out the ResourceDictionary
DrawingImage image = dict[dict.Keys.Cast<object>().ToList()[0]] as DrawingImage;

I could return the image and bind it to the viewmodel property, which returns the iconfilename.xaml. Then I use a converter with the above code to lookup the icon and return it as a DrawingImage.
Or you can assign it as the source of an Image (see my 2nd post below).
UPDATE: 2015.10.08 - It seems Carl didn't get around to the "XAML format example" part of his post.  The XAML would look something like this:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DrawingImage x:Key="SomeUniqueKey">
    <DrawingImage.Drawing>
        <DrawingGroup>
            ...
        </DrawingGroup>
    </DrawingImage.Drawing>
</DrawingImage>
</ResourceDictionary>

Then you could do:
DrawingImage image = dict["SomeUniqueKey"] as DrawingImage;

Or, if you prefer using the Image directly,
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image x:Key="SomeUniqueImage">
    <Image.Source>
        <DrawingImage>
            ...
        </DrawingImage>
    </Image.Source>
</Image>
</ResourceDictionary>

And:
Image someImage = dict["SomeUniqueImage"] as Image;


text:
Q: How to close multiple connections in mongoose In trying to create two databases (using mongoose) in the same index.js, I created multiple connections using the mongoose.createConnection() method. As a result I can't use the mongoose.connection.close() method to close the connections because it only works if you use the mongoose.connection() method in creating your connection.
Does anyone know how I can't close my connections I created with mongoose.createConnection()


text:
Q: How to solve Jmeter server start error on MacBook: "No such file or directory"? I am trying to run Jmeter for a distributed load test. I have multiple PC and Macs to be used as slaves. I configured all other slaved properly, but on one particular Mac I get the following:
/Library/apache-jmeter-3.3\ 2/bin/jmeter-server ; exit;
C02L14PYF6T6-MacBook-Air:~ user$ /Library/apache-jmeter-3.3\ 2/bin/jmeter-server ; exit;
usage: dirname path
/Library/apache-jmeter-3.3 2/bin/jmeter-server: line 32: /jmeter: No such file or directory
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

I have looked on many other resources, but could not find a solution. I even uninstalled Jmeter using Brew and copied the Jmeter binary and directly put it on desktop, but still getting this error.

A: According to source code of jmeter-server, line 32 is :
${DIRNAME}/jmeter ${RMI_HOST_DEF} -Dserver_port=${SERVER_PORT:-1099} -s -j jmeter-server.log "$@"

The error you got tells that DIRNAME is empty. This variable is set line 23 :
DIRNAME=`dirname $0`

I'm not on a mac, but maybe dirname does not exists on you system. Or shell on your system misinterpret back quote.
Plus, I see your path contains space. This is definitely not recommended when one want to use command line and scripts.
You may also edit this jmeter-server to hardcode some parts.

A: When you call jmeter-server ; the ; character is the first argument to JMeter program. first argument is directory name in order to change directory for finding JMeter execution folder.
You don't want to change directory so just execute jmeter-server without extra characters/arguments

A: Finally figured out the issue. I am trying to run V3.3 on a mac.. but for some reason apachejmeter.jar is missing in the version as well as 3.3.2 version. I have downgraded to 3.2.3 version and this has the file in bin folder. Its working fine now.


text:
Q: Installing AWS CLI Version 2 in GitLab-Runner In-order to deploy my Spring-Boot application into AWS ECS, I have the need of installing AWS CLI Version 2 into my GitLab-Runner which is running in AWS EC2 Linux based AMI. I will add below the scripts and stage used to install AWS CLI version 2.
This is the deploy stage and the image used.
deploy:
  image: alpine:3.11
  stage: deploy
  tags:
    - demo-ci
  script:

Below I mentioned the script used to install AWS CLI Version 2 within the above mentioned stage.
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
./aws/install
aws --version

When I am running the script, I get the following issue.
$ ./aws/install
./aws/install: line 78: /builds/sl-psf/SpringDemoECS/aws/dist/aws: not found
You can now run: /usr/local/bin/aws --version
$ aws --version
/bin/sh: eval: line 130: aws: not found

Even though it is mentioned to try /usr/local/bin/aws --version, it doesn't work either.
However there is a workaround and it solved the issue and I will put the code below for that.
variables:
  REGION: "us-east-2"
  REPOSITORY_URL: "############.dkr.ecr.us-east-2.amazonaws.com"
  IMAGE_TAG: "demo-app:0.1"
  GLIBC_VER: "2.31-r0"

[......]

docker-deploy:
  image: alpine:3.11
  stage: deploy
  script:
    - apk add --no-cache python3 py3-pip binutils curl
    - curl -sL https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub -o /etc/apk/keys/sgerrand.rsa.pub
    - curl -sLO https://github.com/sgerrand/alpine-pkg-glibc/releases/download/${GLIBC_VER}/glibc-${GLIBC_VER}.apk
    - curl -sLO https://github.com/sgerrand/alpine-pkg-glibc/releases/download/${GLIBC_VER}/glibc-bin-${GLIBC_VER}.apk
    - curl -sLO https://github.com/sgerrand/alpine-pkg-glibc/releases/download/${GLIBC_VER}/glibc-i18n-${GLIBC_VER}.apk
    - apk add --no-cache glibc-${GLIBC_VER}.apk glibc-bin-${GLIBC_VER}.apk glibc-i18n-${GLIBC_VER}.apk
    - /usr/glibc-compat/bin/localedef -i en_US -f UTF-8 en_US.UTF-8
    - curl -sL https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip -o awscliv2.zip
    - unzip awscliv2.zip
    - aws/install
    - rm -rf awscliv2.zip aws /usr/local/aws-cli/v2/*/dist/aws_completer /usr/local/aws-cli/v2/*/dist/awscli/data/ac.index /usr/local/aws-cli/v2/*/dist/awscli/examples glibc-*.apk
    - apk --no-cache del binutils curl
    - rm -rf /var/cache/apk/*
    - aws --version

I don't think this is the optimal way to install AWS CLI Version 2. It was pretty difficult to do this task and there are various ways suggested. I think that this is a common issue lots of people might have faced. My question is that is there a better way to achieve this or if so then what would be the way?


text:
Q: Show ranking of each result in an array php mysql I've been hitting my head on the wall all day over this one I'm sure what to do. I'm hoping it's not really simple because it's been a struggle for me! I've searched all day long hopefully someone can help me.
I have an html table that shows the fitness test results of every player from a training camp. I have figured out how to display them all along with their name (taken from another mysql table). Now beside each test result I want to add how they rank for that specific test result. Here is the code right now minus the filtering part (I don't think that it's needed to solve this):
The database query is below. It orders the players in the table by positions so that all the defence show up together, all the forwards together, and goalies together for easy viewing by a coach.
//get the camp id for the coach logged in
$getcampid = "SELECT value FROM profile_values WHERE uid = '$user->uid'";
$campid = mysql_query ($getcampid);
$campidrow = mysql_fetch_array($campid);
$coachescamp = $campidrow[0];

$getplayerdata = mysql_query("SELECT * FROM content_type_test

INNER JOIN content_type_player ON content_type_test.field_player_uid=
content_type_player.field_uid

WHERE content_type_test.field_training_camp_nid='$coachescamp'

ORDER BY content_type_player.field_position_value") or die(mysql_error());

$left = true;
while($playerdata=mysql_fetch_array($getplayerdata))
{

echo "", $playerdata['field_position_value'], "	";
echo "", $playerdata['field_last_name_value'],", ",$playerdata['field_first_name_value'], "	";
echo "", $playerdata['field_speed_value'], "	";
echo "Show rank of players speed compared to other players in $getplayerdata query	";
echo "", $playerdata['field_agility_value'], "	";
echo "Show rank of players agility compared to other players in $getplayerdata query	";
echo"
";
}
echo"

";

I need to show the rank of the players speed and agility in the columns where it says "show rank of players...". In total there are 5 more ranks that I need to display in that table that I didn't include to keep thing simple. If I can see how to do it for these two I'll be able to do it for the others.
Of note: Speed and Agility are numbers. The lowest number from the array should be ranked #1.
Thanks for any help this ones been killing me.
EDIT -------------------------------------
Here is the code I have that returns only 1 result
$getplayerdata = mysql_query("SELECT * FROM content_type_test

INNER JOIN content_type_player ON content_type_test.field_player_uid=
content_type_player.field_uid

WHERE content_type_test.field_training_camp_nid='$coachescamp'

ORDER BY content_type_player.field_position_value") or die(mysql_error());

$left = true;
while($playerdata=mysql_fetch_array($getplayerdata))
{

$arrayOfAllData = array();
while($playerdata=mysql_fetch_array($getplayerdata)){
$arrayOfAllData[$playerdata[ID]] = array(field_position_value =>$playerdata['field_position_value'],
                                      field_last_name_value=>$playerdata['field_last_name_value'],
                                      field_speed_value=>$playerdata['field_speed_value']);

}

$sql = mysql_query("SELECT @rownum:=@rownum+1 'rank', * FROM content_type_test, (SELECT @rownum:=0) r
INNER JOIN content_type_player ON content_type_test.field_player_uid=
content_type_player.field_uid
WHERE content_type_test.field_training_camp_nid='$coachescamp'
ORDER BY content_type_player.field_speed_value");

while($playerdata=mysql_fetch_array($sql)){
    $arrayOfAllData[$playerdata[ID]]["field_speed_value"] = $playerdata['field_speed_value'];
}

foreach($arrayOfAllData as $player){
   echo "", $player['field_position_value'], "	";
   echo "", $player['field_last_name_value'],", ",$player['field_first_name_value'], "	";
   echo "", $player['field_speed_value'], "	";
   echo "*I dont know what to put here to display the rank*	";
   echo"
";
}
}
echo"

";

Doing the Print shows one row like this
    Array ( [] => Array ( [field_position_value] => Forward [field_last_name_value] => Tester [field_speed_value] => 4.504 ) )
Also as noted in the one column I don't know what to type to show the rank.

A: OK, since there is no elegant way to do this with 1 MySQL query, I would use multiple querys, combine them into an array and loop through that for your results.  It's a bit of a hack, but will get the job done.
Use your original query, then instead of looping through and displaying right away, loop through and put into array:
$arrayOfAllData = array();
while($playerdata=mysql_fetch_array($getplayerdata)){
$arrayOfAllData[$playerdata[ID]] = array(field_position_value =>$playerdata['field_position_value'],
                                          field_last_name_value=>$playerdata['field_last_name_value'],
                                          field_speed_value=>$playerdata['field_speed_value'])

}

Then get your next MySQL query that will rank the players by field_speed_value
$sql = mysql_query("SELECT @rownum:=@rownum+1 'rank', * FROM content_type_test, (SELECT @rownum:=0) r
INNER JOIN content_type_player ON content_type_test.field_player_uid=
content_type_player.field_uid
WHERE content_type_test.field_training_camp_nid='$coachescamp'
ORDER BY content_type_player.field_speed_value");

This query will add a ranking for each player, now you have to add this ranking as a value in the $arrayOfAllData
while($playerdata=mysql_fetch_array($sql)){
    $arrayOfAllData[$playerdata[ID]]["field_speed_value"] = $playerdata['field_speed_value']);
}

make a new query for each ranking, and add it to your array the same way.  Then when you are all done adding to the array, you can out put like this:
foreach($arrayOfAllData as $player){
   echo "", $player['field_position_value'], "	";
   echo "", $player['field_last_name_value'],", ",$player['field_first_name_value'], "	";
....etc...
}

Hope this helps, Im tired and going to bed, can clarify tomorrow if you have any problems.

A: EDIT: SORRY - This Query will only work in SQL Server, not MySQL.
you can add columns to your sql query that will have the rankings:
SELECT *, ROW_NUMBER() OVER (ORDER BY field_speed_value) AS field_speed_Ranking,
ROW_NUMBER() OVER (ORDER BY field_agility_value) AS field_agility_Ranking
FROM content_type_test
INNER JOIN content_type_player ON content_type_test.field_player_uid=
content_type_player.field_uid
WHERE content_type_test.field_training_camp_nid='$coachescamp'
ORDER BY content_type_player.field_position_value") or die(mysql_error());

This will give you two new columns in your query results, field_speed_Ranking and field_agility_Ranking with each player ranked in order.  Just echo them out the same way you did with the other columns.


text:
Q: Are JAXRS restful services prone to CSRF attack when content type negotiation is enabled? I have a RESTful API which has annotations like @Consumes(MediaType.JSON) - in that case, would the CSRF attack still be possible on such a service? I've been tinkering with securing my services with CSRFGuard on server side or having a double submit from client side. However when I tried to POST requests using FORM with enctype="text/plain", it didn't work. The technique is explained here This works if I have MediaType.APPLICATION_FORM_URLENCODED in my consumes annotation. The content negotiation is useful when I'm using POST/PUT/DELETE verbs but GET is still accessible which might need looking into.
Any suggestions or inputs would be great, also please let me know if you need more info.
Cheers

A: JAX-RS is designed to create REST API which is supposed to be stateless.
The Cross Site Request Forgery is NOT a problem with stateless applications.
The way Cross Site Request Forgery works is someone may trick you to click on a link or open a link in your browser which will direct you to a site in which you are logged in, for example some online forum. Since you are already logged in on that forum the attacker can construct a url, say something like this: someforum.com/deletethread?id=23454
That forum program, being badly designed will recognize you based on the session cookie and will confirm that you have the capability to delete the thread and will in fact delete that thread.
All because the program authenticated you based on the session cookie (on even based on "remember me" cookie)
With RESTful API there is no cookie, no state is maintaned between requests, so there is no need to protect against session hijacking.
The way you usually authenticate with RESTFul api is be sending some additional headers. If someone tricks you into clicking on a url that points to restful API the browser is not going to send that extra headers, so there is no risk.
In short - if REST API is designed the way it supposed to be - stateless, then there is no risk of cross site forgery and no need to CSRF protection.

A: Adding another answer as Dmitri's answer mixes serverside state and cookies.
An application is not stateless if your server stores user information in the memory over multiple requests. This decreases horizontal scalability as you need to find the "correct" server for every request.
Cookies are just a special kind of HTTP header. They are often used to identify a users session but not every cookie means server side state. The server could also use the information from the cookie without starting a session. On the other hand using other HTTP headers does not necessarily mean that your application is automatically stateless. If you store user data in your server's memory it's not.
The difference between cookies and other headers is the way they are handled by the browser. Most important for us is that the browser will resend them on every subsequent request. This is problematic if someone tricks a user to make a request he doesn't want to make.
Is this a problem for an API which consumes JSON? Yes, in two cases:

*

*The attacker makes the user submit a form with enctype=text/plain: Url encoded content is not a problem because the result can't be valid JSON. text/plain is a problem if your server interprets the content not as plain text but as JSON. If your resource is annotated with @Consumes(MediaType.JSON) you should not have a problem because it won't accept text/plain and should return a status 415. (Note that JSON may become a valid enctype one day and this won't be valid any more).

*The attacker makes the user submit an AJAX request: The Same Origin Policy prevents AJAX requests to other domains so you are safe as long as you don't disable this protection by using CORS-headers like e.g. Access-Control-Allow-Origin: *.