text:
Q: How to desplay a waiting message while only one client is connected and running the game when both players are connected? I have made a multiplayer connect4 using pygame and socket.it's working fine but I want to display a waiting message while only one client is connected and when 2 clients are connected i want to run the main game and display the main game board in both clients screens.
In the server side i keep track of all the clients who join. when the second client connects i send a message to all the clients and then in the client side i  set the varible all_connected which is by defult False to True.
and then in my main function i have said if all_connected is False , fill the background color with blue and display a text saying 'waiting for the other player to join' and else if all_connected is True then call the function which contains the main game_board. but it's not working fine.
it basicly shows the waiting message when one client is connected as it's supposed to , but when the other client joins in , the main gameboard displays on the second client's screen but not the first client's. the first client's screen doenst get updated.
I dont know how to fix this problem ? any idea?
update :
here is when the clients recive data from the server.

def client_recive():

    while True :
        try :
            message = client.recv(1024).decode()
            oppon = message.split('-')
            print('reciving:' ,oppon)

            #if the first client connected :
            if oppon != [''] and oppon[0] == 'red':
                board.running = True
                #print(board.running)
                board.player_num = int(oppon[2])
                print(board.all_connected()) #will print False here

            #if second client connected :
            if  oppon != [''] and oppon[0] == 'yellow' :
                board.player = oppon[0]
                board.running = True
                board.ready = True
                board.player_num = int(oppon[2])
                print(board.connected()) #will print True here

                your_turn = True

                #client.send(board.player.encode('utf-8'))
            elif message == "Connection overflow. Max amount is 2":

                client.close()
                board.running = False
                pygame.quit()
                break

            else:
                #oppon = message.split('-')
                if oppon != ['']  and len(oppon) == 4:
                    board.move(int(oppon[1]),oppon[2])
                  #  print(board.valid_move , oppon)
                    if oppon[3] == 'True' and board.valid_move :
                        your_turn = True
                        #print(your_turn)
                        if oppon[2] == 'red':
                            board.player = 'yellow'
                        elif oppon[2] == 'yellow':
                            board.player = 'red'
                    #if oppon[2] == False and board.valid_move

        except socket.error as error :
            print(str(error))
            client.close()
            break
recive_thread = threading.Thread(target=client_recive)
recive_thread.start()

if board.all_connected():
        board.game_board()
        board.turn_viewer_text(board.player)
    else:
        screen.fill(pygame.Color('blue'))
        waiting_text = board.big_font.render(f'waiting for the opponent ...',True,pygame.Color('white'))
        screen.blit(waiting_text,(screen_x//2,screen_y//2))

    while board.running :
        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                board.running=False
                pygame.quit()
            #print(your_turn)
            if  event.type == pygame.KEYDOWN and your_turn:
                if event.key == pygame.K_1 or event.key == pygame.K_KP1:
                    col = 1
                    board.move(col,board.player)
                   # print('yes')
                #    pass
                if event.key == pygame.K_2 or event.key == pygame.K_KP2:
                    col = 2
                    board.move(col,board.player)
                if event.key == pygame.K_3 or event.key == pygame.K_KP3:
                    col = 3
                    board.move(col,board.player)
                if event.key == pygame.K_4 or event.key == pygame.K_KP4:
                    col = 4
                    board.move(col,board.player)
                if event.key == pygame.K_5 or event.key == pygame.K_KP5:
                    col = 5
                    board.move(col,board.player)
                if event.key == pygame.K_6 or event.key == pygame.K_KP6:
                    col = 6
                    board.move(col,board.player)
                if event.key == pygame.K_7 or event.key == pygame.K_KP7:
                    col = 7
                    board.move(col,board.player)
                    print(7)

                sending_data = '{}-{}-{}-{}'.format(board.row_counter,col,board.player,your_turn)
                print('sending: ' ,sending_data)
                client.send(sending_data.encode('utf-8'))
                if board.valid_move :
                    your_turn = False
                    if board.player == 'red':
                        board.player = 'yellow'
                    elif board.player == 'yellow':
                        board.player = 'red'


text:
Q: Get template variable in onCreated in Meteor I am rendering a template with Blaze.renderWithData(Template.templateName, { key: value });
I can get the value in my template with {{key}}, but I cannot get the value in my js code.
I have tried
Template.templateName.onCreated( () => {
  console.log(Template.instance().key);
});

but the variable is undefined.

A: You can use
this.data.key

or
Template.instance().data.key

Cheers

A: It should be
Template.instance().data['your-key']

If you have doubt about what is the value, put the break on the source code of the chrome developer tools or firebug and try to debug. This is the client side, thus all the code will be available

A: Data passed to template is available on this in onCreated function,
so this should works:
 Template.templateName.onCreated( () => {
      console.log(this.key);
 });

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do I always get an abundance of just a couple different metal ores? When I embark I specifically look for shallow and deep metal with at least a little soil in hopes of getting iron. Which half the time i do get iron and maybe one other different type of metal. The other half of the time i end up with all gold and usually silver. Am i just not looking hard enough?  I feel like there should be a wide variety metals in a certain area.
Do i always get an abundance of just a couple different ores and miss out of getting to use the rest?

A: Generally, yes, you will get a large number of a couple metals. This is one reason that trade is so important. The density of ores, can, however, be changed before world creation with one of the world customization options.


text:
Q: What does this new icon mean? I'm wondering what this new icon means. The number, border and colors change size and shape between players.

A: That icon shows a player's Endorsement level, while the colours represent how many endorsements of each kind that player has received:

*

*Sportsmanship in green

*Good Teammate in purple

*Shot Caller in orange

You can endorse other players at any time after a quick play or competitive match has ended but before ending the next match that allows endorsements.
Some arcade game modes also support endorsements, in both competitive and non-competitive versions:

*

*3v3 Group Elimination

*Capture the Flag

*Lúcio Ball

*Team Deathmatch

For more information, visit the official website's page on endorsements.


text:
Q: fastest method to get indices of first and last common elements between lists I have two sorted lists
x = [-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10]
y = [3,4,5,6]

Between these x and y I would like to return imin = (6,0) and imax = (9,3). If these lists do not share any elements, I would like to return imin = None and imax = None.
A solution is
def inds(x,y):
    arr = [(i,j) for i,xx in enumerate(x) for j,yy in enumerate(y) if xx==yy ]
    if arr!=[]: # to obtain proper None output
        imin = (min(i for i,_ in arr), min(j for _,j in arr))
        imax = (max(i for i,_ in arr), max(j for _,j in arr))
    else:
        imin = None
        imax = None
    return (imin,imax)

This does a lot of unnecessary computation (O(n**2)) and is a bottleneck of one of my programs. Can anyone suggest something faster?
ADDITIONAL (NON-MINIMAL EXAMPLE) INFO
If it helps, I actually have a list of objects.
objects = [(A1,B1),(A2,B2)]

x and y would be attributes of each element of this objects list like so:
x = objects[0][0].attrib
y = objects[0][1].attrib

and I actually want to generate
[(imin1,imax1),(imin2,imax2)]

Which could come, for example, from
def attribs(A,B):
    return (A.attrib,B.attrib)

[inds(*attribs(*v)) for v in objects]

note: I added a numpy tag just because I'm open to using numpy for this if it's faster.

A: This should be what you are after
c = set(x).intersection(y)  # O(n) time
def get_first(l):
    return next((idx for idx, elm in enumerate(l) if elm in c), None)  # O(n) time
imin = (get_first(x), get_first(y))
imax = (len(x) - get_first(x[::-1]) - 1, len(y) - get_first(y[::-1]) - 1)

From here onwards you can do a few tweaks but it will still run O(n)

A: Using np.intersect1d and returning the indices, you can do the following
idxes = np.stack(np.intersect1d(x,y, return_indices=True)[1:])
ix = tuple(idxes[:,0])
iy = tuple(idxes[:,-1])

>>> ix
(6, 0)
>>> iy
(9, 3)

Explanation
idxes is a 2d array of the indices where there are intersections between your two arrays:
>>> idxes
array([[6, 7, 8, 9],
       [0, 1, 2, 3]])

So you can just take the first and last using
ix = tuple(idxes[:,0])
iy = tuple(idxes[:,-1])

A: You can also sort the intersection list and use .index() to find out the indices.
z = list(set(x).intersection(set(y))) # O(n)
z.sort() # O(nlogn)

imin = (x.index(z[0]), y.index(z[0])) # O(n)
imax = (x.index(z[-1]), y.index(z[-1])) # O(n)


text:
Q: How to remove tab stop from iframe? How can I remove tab stop from an <iframe>? The <iframe> is hosted on my domain.
I have tried following code:
var objIFrame = document.getElementById('my_iframe');
if (objIFrame != null) {
   objIFrame.setAttribute('tabindex', '-1');
}

But still I get iframe focused.

A: An iFrame does'nt really support tabbing or selecting, it's normally the document or body inside the iFrame that is selectable. Try something like:
var objIFrame = document.getElementById('my_iframe');
    objIFrame.contentDocument.setAttribute('tabindex', '-1');
    objIFrame.contentDocument.getElementsByTagName('body')[0].setAttribute('tabindex', '-1');

A: I studied Stripe Elements as an example to figure this out - they use <iframes> to collect Credit Card numbers and have a smooth tab ring through all their fields.
No amount of setting tabindex on anything did it for me so I opted to do it in JavaScript instead. I fixed it by listening for the <iframe>'s window to be focused, and then redirecting that focus to the element I wanted it to. This requires you to be in control of the <iframe>'s contents.
window.addEventListener('focus', function() {
  document.getElementById('myInput').focus();
})

Here's an example:
index.html
<html>
  <body>
    My input
    <input type="text" />
    <iframe src="https://www.example.com/iframe.html" />
  <body>
</html>

iframe.html
<html>
  <body>
    More inputs
    <input type="text" />
    <input type="text" />
    <input type="text" />
    <script>
      window.addEventListener('focus', function() {
        document.getElementById('myInput').focus();
      })
    </script>
  <body>
</html>

I noticed this behavior was unique to Internet Explorer 11 and Firefox 76, but didn't affect Chrome 81 or Edge 81.


text:
Q: Mongodb Embedding structure and search If I have a collection: Visitor and I would like to embed an array of Visits in it, then it will look something like this:

Visitor1
->Visit 1
->Visit 2

Visitor2
->Visit 1
->Visit 2

*

*Is this a good structure ?

*When I will have millions of documents, I will have to first look for the visitor then add a visit, is this structure efficient ?

*How do I display all visits for all visitors ?

A: it can be efficient depending on what you have to do more often. The structure in and by itself is fine. You always getting all visits for a single visitor for "free" when you query a visitor is the biggest advantage so you get all visits for a single visitor pretty easy. It also means you don't need a visits collection which cleans up your schema.
Here are example implementations to the operations you require :
Adding a visit :
db.visitors.update({_id:<visitorId>}, {$push:{visits:<newVisit>}})
Removing a visit :
db.visitors.update({_id:<visitorId>}, {$pull:{visits:{visitId:<visitId>}})
If you meant displaying all visits of all visitors combined there's no direct way to do so currently. You can do so with either a distinct operation and some application logic to unwrap the individual arrays or use m/r. In 2.2. there will be an aggregation framework which can do that just fine.
There are some things to consider though :

*

*Documents have a 16mb limit. If you can have enough visits to reach this limitation then you require a seperate visit collection.

*Querying for some visits of a specific visitor is not possible. You always query top level documents so if a user has 14,000 visits and you only need a specific few you'll have to retrieve the entire document. For paging some of this can be handled by using $slice.

*Modifying multiple visits for a single visitor with one update can be a tricky without a seperate visits collection. You can only address one array element per update through the positional operator $.

Hope that helps.


text:
Q: [Vue warn]: Unknown custom element:  - did you register the component correctly? I'm creating a unit test for a Vue component (inside a Nuxt app) like this:
<template>
    <BaseHeader>
        ...

        <LazyHydrate when-visible>
            <LazyNewsletter />
        </LazyHydrate>
    </BaseHeader>
</template>

<script>
import BaseHeader from '@acme/components/BaseHeader/BaseHeader.vue'
import Newsletter from '@/components/Newsletter/Newsletter.vue'

export default {
    name: 'TheHeader',
    components: {
        BaseHeader,
        Newsletter
    },
}
</script>

but I'm getting this warning in the console when running the test:
console.error
    [Vue warn]: Unknown custom element: <LazyHydrate> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

LazyHydrate is a component from the package vue-lazy-hydration and it's already configured in the nuxt app.
Does anyone know what's happening here?
T.I.A.
I tried to use mount instead of shallowMount, but I get the same error.


text:
Q: Why is my CNN model not learning anything? (tensorflow) I've been trying to make an image classifier base on this tutorial
I have changed a few things in it, which I didn't think would completely break the learning pattern but they did... The accuracy calculations are consistently about as good as random guesses, with no upward curve, not even a slow one.
As you could see in the code, the only major changes I made was using my own data-set instead of the MNIST data-set, and my data is pictures of characters of 89 classes, not just 10. I apply random noise and distortions before batching them to the trainer, and I have about 100,000 examples of each of the 89 classes.
I have commented next to the only changed lines to help you read the changes
Code (python):
def model(features, labels, mode):

    #Change from the tutorial - 36*36 images instead of 28*28
    input_layer = tf.reshape(features, [-1, 36, 36, 1])

    conv1 = tf.layers.conv2d(inputs=input_layer, filters=32, kernel_size=[5, 5], padding='same', activation=tf.nn.relu)
    pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
    conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu)
    pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

    # Change From the tutorial - 9*9*64 instead of 7*7*64 to match different image size
    pool2_flat = tf.reshape(pool2, [-1, 9 * 9 * 64])

    dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
    dropout = tf.layers.dropout(inputs=dense, rate=0.4, training=mode == learn.ModeKeys.TRAIN)

    # Change from tutorial = 89 classes instead of 10
    logits = tf.layers.dense(inputs=dropout, units=89)
    onehot_labels = tf.one_hot(indices=tf.cast(labels, tf.int32), depth=89)

    loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=logits)
    train_op = tf.contrib.layers.optimize_loss(
            loss=loss,
            global_step=tf.contrib.framework.get_global_step(),
            learning_rate=0.001,
            optimizer='SGD'
    )
    # Generate Predictions
    predictions = {
        "classes": tf.argmax(input=logits, axis=1),
        "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
    }

    return model_fn.ModelFnOps(mode=mode, predictions=predictions, loss=loss, train_op=train_op)

I thought that the network parameters are maybe to small to handle 36*36 pictures and 89 classes, so I tried giving the conv layers more features, or increase the dense layer nodes, but nothing seems to change. The only results in tensorboard I see are of 1%-1.5% accuracy, which fit well with random guesses on 89 classes.
I'm a real newbie in tensorflow and machine learning so please be gentle with me, and tell me please what i'm doing wrong.
Edit: Training code:
def train(batch_size, steps):
    config = get_config()
    config.mode = 'train' # just for the example
    # Generate training data
    if config.mode == learn.ModeKeys.TRAIN:
        x, y = generate(batch_size * steps)
    print(y) # prints correct labels in range 0-89
    logging_hook = tf.train.LoggingTensorHook(tensors={"Probabilities": "softmax_tensor"}, every_n_iter=50)
    char_classifier = learn.Estimator(model_fn=model, model_dir=mydir)

    # Train!
    if config.mode == learn.ModeKeys.TRAIN: #assume this is always true in the example here
        char_classifier.fit(x=x, y=y, batch_size=batch_size, steps=steps, monitors=[logging_hook])
    accuracy = learn.MetricSpec(metric_fn=tf.metrics.accuracy, prediction_key="classes")

    # Evaluate!
    x, y = generate(1000)
    eval_results = char_classifier.evaluate(x=x, y=y, metrics={'accuracy':accuracy})

Also, sample images:


text:
Q: Are auto-downloaded malicious .dmg app files a security risk if they are never opened? I visited a page to stream a TV show, and upon clicking the search result link got the following pop-up:

I clicked OK, as nothing on Chrome was available, and when I did that, Chrome auto-downloaded a file called FlashPlayer.dmg.
Here is a picture of that file:

I didn't open the .dmg file or click on it at all.  Instead, I immediately went to my downloads folder, deleted the file, and then emptied my trash.
I then went to see my downloads on Chrome; the URL seems to be something like www.makeymcmacface.com/prod/... (which Google indicates belongs to the Mac.Trojan.Genieo.33 type of adware).
My question is this: If I download a malicious .dmg file, but don't click on it to install it, am I safe? Or is there a possibility that by simply visiting a website that auto-installs a .dmg file, I could have compromised my security?

A:
If I download a malicious .dmg file, but don't click on it to install it, am I safe?

You are safe. The .dmg (disk image) file is not the actual installer. The .dmg must be double-clicked to install it before it can run any code. Even if you double-click it (so long as you leave the security feature Gatekeeper on), you must approve both the downloaded from the web alert and the authentication prompt to actually permit the install to proceed.

Is there a possibility that by simply visiting a website that auto-installs a .dmg file, I could have compromised my security?

No, your security is not compromised unless you manually install the file. The reason for this is that a website can only offer a .dmg file for download. There is no "auto-install" for a .dmg app file. You may click on a link (or a button) to start the download, but disk images themselves are not "installed" by the download process—meaning they can't run any code on your Mac until you type in your password to install them (again, because of macOS's built-in security feature Gatekeeper). The disk image is merely saved to your designated folder (typically Downloads) then waits for you to take further action by double-clicking on it to mount it. For any code from that app to be run, you have to authenticate with your password.

Bonus tip: When a website tells you that your flash player is out of date by way of a pop-up like you've shown, that should be an automatic red flag! Outdated Flash Player alerts are almost never legitimate. Instead of clicking on that OK button on the notification like you did, you should force quit your browser: choose Force Quit from the Apple menu in the menubar ()—or just press Command+Option+Esc—then select Chrome/Safari and hit Force Quit. Hold down Shift while opening Safari to prevent the website from reloading.

A: You are always safe when you don't open the DMG as the app is in a container and it can't execute itself.
Security tips regarding downloads:

*

*You always get a popup question of OS X if you want to open this file.

*OS X is standard secured to only open applications that are downloaded from the App Store. Even if you want to install a application that is not from the App Store you still need to disable the security (via Settings > Security and Privacy > press the lock in the bottom left corner, enter your passcode and set 'Anywhere'.)

A: I'm going to make this easier for you to understand.

*

*Am I safe, if a suspicious file was downloaded but never opened or installed in my Mac?

Yes you are safe.

*Am I safe, if I was redirected to an unknown website, when I clicked on a notification shown on another website?

No, not really. There are 99% chances, that you get infected by 0day exploits used by hackers, to turn your computer into their bot. In order to protect yourself from such hack attempts and attacks, always use popup & ad blockers, and avoid visiting sites, which redirect or opens popups.

A: You are probably safe
As long as you don't open or install anything it is pretty hard to get a virus.
If you haven't disabled gate keeper (an internal system process that makes sure that software from unidentified developers does not open unless you type in an admin password to confirm that they are safe) you are 99.99% safe.
For future reference: A .dmg file is a disk image file. Even when you open a .dmg, it will only mount the disk. This means that it opens up a little folder on your desktop kinda like when you put a CD in your mac. You can't edit the folder, you can only eject it. To eject the mounted disk, just click the little eject button, or drag it to the trash can.
Here is a quote from wikipedia  about disk images

An Apple disk image allows secure password protection as well as file compression, and hence serves both security and file distribution functions; such a disk image is most commonly used to distribute software over the Internet.

HOWEVER:
If your browser keeps opening up these malicious advertisements, you may have adware already in your computer (check through your chrome extensions). Any extension that installs a new search engine is likely adware.
Pro tip: Install Adblock. It is damn near impossible to get a virus with Adblock unless your are actively seeking out malicious websites. Adblock will prevent sites from opening up these annoying pop-ups and will remove ads from youtube and basically every other site on the internet. https://chrome.google.com/webstore/detail/adblock/gighmmpiobklfepjocnamgkkbiglidom?hl=en-US

A: All the answers here are great, but IMHO, all you need is to run some trusty anti-malware software like Malwarebytes.


text:
Q: How to verify users email with token generator link for signup in django webapp I am doing a web app in Django. I hardly tried to create a TokenGenerator for verifying the user's email to activate the user's account
coming to the problem,

*

*how to send the verification email to the user account while
signup. while signup, users can receive a verification link email
with a token generator

*the user has to input the password at the time of account signup

*After verifying the email user can log in to the respective page via their mail id and password

*while login it should check whether an email is present in the DB
(DB will be updated with user emails )

A: for the first question, Django has built-in functions and classes for sending emails, you can check them here: https://docs.djangoproject.com/en/3.2/topics/email/ and this post will help you send and email: https://dev.to/yash2115/how-to-send-e-mail-in-django-37ge, and if you want sen an email for any user's sign up you have to use signals, check it here: https://docs.djangoproject.com/en/3.2/ref/signals/
other questions are all related and they are pre-built in Django, these links will help you: https://learndjango.com/tutorials/django-login-and-logout-tutorial
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication
repositories which may help:

*

*https://github.com/shoukreytom/pdfstack

*https://github.com/shoukreytom/notes

*https://github.com/shoukreytom/blog (advanced - apis)

*https://github.com/mitchtabian/Food2Fork


text:
Q: php empty post array with file upload <form method="post" enctype="multipart/form-data">

Add video

Name

        <input type="text" name="title"/>

Video

        <input name="video" type="file" />

<button>Add</button>

</form>

This is the form I use to upload a video file and a title, so when I DON'T upload a file the $_POST variable is filled with form data, but If I upload a file the $_POST variable is empty, why is that?

A: You are looking in the wrong spot, try looking in $_FILES not $_POST

A:
<button>Add</button>

should be

<input type="submit" name="submit" value="Add">

Using this all the post data is accessible as
$_POST and file data with $_FILES


text:
Q: How to deny creating empty log file with be.file in Pantheios? 1)be.file backend has a feature - messages added before _be_file_set_filename() are not lost and will be appended to log later.
2)_be_file_set_filename opens file immediately => if no entries was added, emty file will be created
Question: how to suppress creating empty file (create file only when first log entry appended) and save feature 1) ?

A: Use the flag PANTHEIOS_BE_FILE_F_DELETE_IF_EMPTY, described here.
My guess is that the file is created synchronously to avoid the less-desirable situation where a log file cannot be created while a process is running. If you really want that, maybe add the functionality and supply back to the project?

A: I've solved this problem by writing custom backend - wrapper over be.file


text:
Q: SSH tunneling in an airport being at home, I know how to establish ssh tunnels between the work gateway. The main thing is for the gateway, to be able to establish a ssh connection with my machine at home. I do this setting the NAT options of the wifi router.
But sometimes I am at the airport. Here, the wifi connection does not allow to establish this kind of connections.
Do you know any other way to do it?
Thanks

A: When at an airport, you typically have to pay for internet connection. When you open a browser, you will be taken to a page where you can buy connection, or type in a username/password if you have a subscription. Unless you do so first, any network communication will be disabled.
If that doesn't help, try changing the SSH port no. to one used for stuff that would normally be allowed, e.g. SMTP or POP3 port. Port 81 is often also a good candidate.

A: Are you trying to create an outbound tunnel from your PC to work, or an inbound tunnel from work to your PC?
If the former, then you're probably running into a situation where the provider's firewall is blocking everything other than HTTP/HTTPS over specific ports. This is unusual: I can't remember the last time that I've had arbitrary outbound traffic blocked, and usually have no problem using SSH to get to my home machine. If you are getting blocked, then some sort of HTTP tunneling (as suggested by other posters) would be the only option -- although I can't begin to imagine the overhead this must imply.
If the issue is that you can't open a connection from work to your airport-situated laptop (and I'm assuming this is what you want since you talked about NAT settings), well, you're going to be out of luck for a direct connection. You almost certainly have a private IP behind the airport's firewall, so there would be no way to route packets to you.
The alternative is to establish two tunnels, with a trusted host (your home machine) in the middle. You'll need to open two ports in your firewall: your normal SSH port (22, but see below), and another port -- say, 2201. From work, open a reverse tunnel to your home machine, using an argument such as 2201:localhost:22 -- all connections to port 2201 on your home machine will be tunneled to port 22 on your work machine. Then open a forward tunnel from your laptop to your home machine, using an argument such as 22:localhost:2201 -- all connections to port 22 on your laptop will be forwarded to 2201 on the home machine.
This is, of course, not an optimal setup. Not only do you have a handoff in the middle, but if you have ADSL (like I do) you'll be hit by the slow upload speeds. All-in-all, traditional VPN is probably a better choice (again an assumption: you're using SSH because your traditional VPN is too slow).

On a side note: opening port 22 on your home firewall is not a good idea: sooner or later you will be attacked. Even if it doesn't lead to getting hacked, the attackers will chew up bandwidth and disk space (the first and only time it happened to me, the auth log grew to many megabytes within the space of an hour -- then I hit slapped myself for being stupid and closed the port -- doesn't matter that my passwords aren't subject to dictionary attack, it's still a bad idea to leave doors unlocked).
Edit: to get sshd to listen to additional ports, edit the file /etc/ssh/sshd_config (Windows users, you're on your own), and add additional Port directives (look for the existing "Port 22" entry):
# What ports, IPs and protocols we listen for
Port 22
Port 2201

A: Unless I misunderstand your question, the airport firewalls are blocking your outgoing connections on port 22. In order to bypass this, tunnel your ssh connections over DNS: http://www.boingboing.net/2004/06/21/tunneling-ssh-over-d.html
Note that in doing so you will almost certainly be able to bypass their "paid-network" systems - simply establish this connection then tunnel your HTTP connections through it.
If bypassing their payment scheme is your goal, you'll get a far better connection if you sit in an area where others have paid, and run airodump-ng or the like to find the mac address of someone sending/receiving a lot of packets with one of these paid networks. Simply spoof his mac address and you'll have internet access.

<morals>
Both of the above techniques are heavily in the moral grey-area. Piggybacking on someone else's connection may even be illegal, I'm not sure, but in any case you will slow down his service, effectively stealing bandwidth from him. While getting free internet via ssh-over-dns does not negatively impact the paid services of others, you are still utilizing resources the company must pay for and receiving a paid service for free, so I would suggest first paying for their service even though it is not necessary, and THEN creating the tunnel. Also consider that the airport might be blocking outgoing 22 for a good reason (although god only knows what that might be).
These are all things you should consider before trying to acquire a paid service for free, or trying to expand your service beyond what the provider offers.
</morals>

A: I recommend the 'soht' project to create tunnels over HTTP.
You have to know the proxy hostname and port.
At home you need a running tomcat server with 'soht' deployed, maybe in conjunction with an apache reverse-proxy.


text:
Q: Ionic 5 Web App Chrome CSS Issues (sc-ion class added) We ran ionic build --prod for an Ionic Angular project to generate the www folder on a Debian 10 server. Set up the domain and everything works properly.
The problem is that when opening the app in Chrome and sometimes in Safari as well on desktop, the icons, buttons and some other elements don't show up the same as on localhost when testing with ionic serve. Specifically, a new class is added to some elements "sc-ion" that causes problems in the UI (e.g. the icons don't have the right line-height, the buttons' text has a different color, etc.). Please see below some screenshots.
Do you know how we can remove the sc-ion class and keep the styling consistent with what gets displayed with ionic serve on localhost? I look forward to hearing your feedback.
Thanks for your help,
Andy

A: Hotjar was causing the issues.


text:
Q: Why doesn't nginx location check if the uri match any regular expression before prefix check? through the nginx doc

To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used. If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used.

Why doesn't nginx location check if the uri match regular expression before prefix check ? and i think it's faster than now?

A: I cannot state why the designers implemented Nginx in any particular way, but...
The prefix check is optimised to be very fast.
And, if the location identified during the prefix check is marked with the ^~ modifier, scanning the regular expressions is no longer required.


text:
Q: Mysql PHP Search Inner Join I'm using MYSql database that outputs like this from my inner join query:

Using this query (It works fine)
$result = mysql_query( "
select
   `account`.`name`, `customfield`.`value`, `note`.`occurredondatetime` noteid
       from  (`note`, `activity`, `ownedsecurableitem` ownedsecurableitem1)
left join `activity_item` on `activity_item`.`activity_id` = `activity`.`id`
  left join `item` on `item`.`id` = `activity_item`.`item_id`
    left join `securableitem` on `securableitem`.`item_id` = `item`.`id`
left join `ownedsecurableitem` on `ownedsecurableitem`.`securableitem_id` = `securableitem`.`id`
  left join `account` on `account`.`ownedsecurableitem_id` = `ownedsecurableitem`.`id`
    left join `_user` on `_user`.`id` = `ownedsecurableitem1`.`owner__user_id`
left join `customfield` on `customfield`.`id` = `account`.`salecyclecstm_customfield_id`

where (`account`.`name` IS NOT NULL)
  and `activity`.`id` = `note`.`activity_id`
    and `ownedsecurableitem1`.`id` = `activity`.`ownedsecurableitem_id`
      and (`note`.`occurredondatetime` IS NOT NULL)
       and name='".$_POST['query']."'";

 ORDER BY occurredondatetime DESC

")

 or die("SELECT Error: ".mysql_error());
  print "
\n";
   $account = "Account";
    $sale = "Sale Cycle";
     $date = "Date";
      print "\t<bold>$account	\n";
       print "\t<bold>$sale	\n";
 print "\t<bold>$date	\n";
  while ($get_info = mysql_fetch_row($result)){
   print "
";
    print "
\n";
     foreach ($get_info as $field)
      print "\t$field	\n";
       print "
\n";
        }
         print "
\n";

My question is:
How would I create a form (Textbox input) that I can search the Account and it will out the Sale Cycle and Date fields (NOT IN  A TABLE)? Ideally I would like it to output on the same page, so Java or Ajax?
I have : HTML
<form name="form1" id="form1" method="post" action="search.php"> //change here
Select Name :
<input type="text" name="query" />
<input type="submit" name="submit" id="submit" value="search" />
</form>

PHP
$query=mysql_query($select) or die($select);
$numrow=mysql_num_rows($query);
if($numrow != 0)
{
while($row=mysql_fetch_array($query))
{
<?php echo $row['name'];
<?php echo $row['SalesStages'];

A: First of all your php coding is wrong.You are using <?php at unwanted places.Please remove it and you have to write a query before you execute it.
<form name="form1" id="form1" method="post" action="search.php"> //change here
Select Name :
<input type="text" name="query" />
<input type="submit" name="submit" id="submit" value="search" />
</form>

$query="select * from table where Account='".$_POST['query']."'";
$result = mysql_query($query) or die (mysql_error());
$numrow=mysql_num_rows($result);

while($row=mysql_fetch_array($query))
{
 echo $row['name'];
 echo $row['SalesStages'];
}

A: You can create dynamic tables with javascript, here is an example: http://listjs.com/ It allows you to search and sort.


text:
Q: "w()", "n()" in Javascript source code in browser Sorry for such silly question, but I am new to javascript and frontend development and struggling with understanding how the javascript code executes in browser.
In my developer environment, I have javascript function like this:
this.publishDataBeforeDispose = function() {
            if (!this.isEnded) {
                segmentStop_();
                publishFinalData_();
            }

However, If I go to prod webpage of our website and try to search across all javascript files in Chrome's Source tab in Dev console, the code there looks like this:
this.publishDataBeforeDispose = function() {
    this.isEnded || (n(),
    w())
}

What is the n() and w() stands for? How can I get to publishFinalData_() method in order to put breakpoint inside this method or change the code of this function right in browser?
Also, I noticed, that js code in the Source tab has different variables like  "a","c","e","d":
  a.publish(),
  c = d("someValue1", "", 1),
  e(c),
  c = d("someValue2", "", b),
  e(c),

How this happens? Is there any online resources that can help me answer my whys for dummies like me?

A: The source code in browser is compressed, and all the scoped function's name and the variable's name have been replaced by simple words. If you want to debug, you can operate before it was compressed. You can debug in local code before publish online.


text:
Q: ToC content spacing and related formatting I'm working in memoir class and creating ToC with both short and (sometimes very) long chapter title. I need to:

*

*Adjust horizontal spacing between part\chapter number and the title so they won't be overlapped, no matter how long the digits\numbers are. The left part of longer-number title doesn't have to be aligned with the shorter one. I prefer the spacing would be automatic/adjustable (depends on the part or chapter digit/number). Thanks.

*Sometimes there's an unwanted vertical spacing between two chapter title in random.
What is the proper way to fix them? I've tried to search for same problems here, but still no luck. Accident/unwanted vertical spacing is still bothering. Thanks.
\documentclass[12pt,twoside]{memoir}
\usepackage[paperwidth=140mm, paperheight=210mm, margin=20mm]{geometry}
\usepackage{titletoc}

\renewcommand\thepart{\arabic{part}}

% simulate larger part and chapter number
\setcounter{part}{50}
\setcounter{chapter}{1200}

\begin{document}

\tableofcontents

\part{This is My First Part}
\chapter{This is first chapter}
\chapter{This is very very long chapter title}
\chapter{Next chapter goes here}

\part{This is My Second Chapter}
\chapter{Very long chapter title also goes here}
\chapter{Another chapter goes here}
\chapter{Another chapter goes here}
\chapter{Another chapter goes here}

% ...and so on...

\end{document}

UPDATE:
In addition to my Pastebin, here's the replicated main.tex.
Hope this helps. Thank you.
\documentclass[12pt,twoside]{memoir}
\usepackage[paperwidth=140mm, paperheight=210mm, margin=20mm]{geometry}
\usepackage{libertine}
\usepackage{graphicx}
\usepackage[svgnames]{xcolor}
\usepackage{framed}
\usepackage{fourier-orns}
\usepackage{bbding}
\usepackage{pdfpages}
\usepackage{lipsum}

% quote
\newcommand*\openquote{\makebox(25,-22){\scalebox{5}{``}}}
\newcommand*\closequote{\makebox(25,-22){\scalebox{5}{''}}}
\colorlet{shadecolor}{Azure}

\makeatletter
\newif\if@right
\def\shadequote{\@righttrue\shadequote@i}
\def\shadequote@i{\begin{snugshade}\begin{quote}\openquote}
\def\endshadequote{%
  \if@right\hfill\fi\closequote\end{quote}\end{snugshade}}
\@namedef{shadequote*}{\@rightfalse\shadequote@i}
\@namedef{endshadequote*}{\endshadequote}
\makeatother
% END quote setting

\usepackage{type1cm}
\usepackage{lettrine}
\usepackage{pdfpages}

\chapterstyle{dash}

\usepackage{textcomp}
\usepackage{gensymb}

\renewcommand{\cftchapterfont}{\normalfont}

% ToC Setting
% http://tex.stackexchange.com/questions/201358/styling-toc-dot-leader-using-emdash-and-other-formatting-requirements
% Redefinitions of \part-entry in ToC
% \renewcommand{\cftpartname}{Part~}
\renewcommand{\cftpartname}{Part~}
\renewcommand{\cftpartaftersnum}{:}
\renewcommand{\cftpartleader}{---}
\renewcommand{\cftpartformatpnum}[1]{%
  \cftpartformatpnumhook{#1}%
  {\cftpartpagefont #1}}
\renewcommand{\cftpartafterpnum}{\hfill\null}

% Redefinition of \chapter-entry in ToC
% \renewcommand{\cftchaptername}{Chapter~}
% \renewcommand{\cftchapteraftersnum}{:}
\renewcommand{\cftchaptername}{}
\renewcommand{\cftchapteraftersnum}{.}
\renewcommand{\cftchapterleader}{---}
\let\oldcftchapterfont\cftchapterfont
\renewcommand{\cftchapterfont}{\oldcftchapterfont\mdseries}
\renewcommand{\cftchapterformatpnum}[1]{%
  \cftchapterformatpnumhook{#1}%
  {\cftchapterpagefont #1}}
\let\oldcftchapterpagefont\cftchapterpagefont
\renewcommand{\cftchapterpagefont}{\oldcftchapterpagefont\mdseries}
\renewcommand{\cftchapterafterpnum}{\hfill\null}

% Distance between part and chapter
\setlength{\cftbeforepartskip}{1em} % part
\setlength{\cftbeforechapterskip}{3pt} % chapter

% Arabic-style page numbering
% http://tex.stackexchange.com/questions/129592/add-parts-to-the-table-of-contents
\renewcommand\thepart{\arabic{part}}

% change font size of ToC item & number
% \renewcommand{\cftpartfont}{\Large\bfseries}
\renewcommand{\cftpartfont}{\normalsize\bfseries}
\renewcommand{\cftpartpagefont}{\normalsize\bfseries}

% GOOD (by Werner)
% http://tex.stackexchange.com/questions/201940/toc-content-spacing-and-related-formatting?noredirect=1#comment470627_201940
\renewcommand{\partnumberlinebox}[2]{#2 }
\renewcommand{\chapternumberlinebox}[2]{#2 }

% Past:
%\setlength{\cftchapternumwidth}{2em}
%\setlength{\cftpartnumwidth}{2em}

% --- END ToC settings

% RUNNING HEADER
% The following code have been found in Peter Wilsons Memoir manual in chapter 7 (page127)
\makepagestyle{My_pagestyle} % Create a new pagestyle

% Following code to edit the pagestyle
\makepsmarks{My_pagestyle}{\nouppercaseheads

% This is where we specify what \leftmark and \rightmark contains
%\createmark{chapter}{both}{nonumber}{}{\space}
%\createmark{section}{right}{nonumber}{}{\space}
% Change "shownumber" to "nonumber" if you don't want the chapter/section number displayed at the header.
\createmark{title}{left}{nonumber}{}{\space}
\createmark{chapter}{right}{nonumber}{}{\space}
\createplainmark{toc}{both}{\contentsname}
\createplainmark{lof}{both}{\listfigurename}
\createplainmark{lot}{both}{\listtablename}
\createplainmark{bib}{both}{\bibname}
\createplainmark{index}{both}{\indexname}
\createplainmark{glossary}{both}{\glossaryname}}
% Might want to keep those, see the manual for further information.

% The following is where you tweek your header
% http://hstuart.dk/2007/06/12/styling-the-page-footer-and-header/
% For verso pages
\makeevenhead{My_pagestyle}{\normalfont\thepage\hskip.5cm\vrule\hskip.5cm\footnotesize\Booktitle}{}{}
% For recto pages
\makeoddhead{My_pagestyle}{}{}{\footnotesize\rightmark\hskip.5cm\vrule\hskip.5cm\normalfont\thepage}

% Activate your new pagestyle
\pagestyle{My_pagestyle}

% --- END

% The 'Part' page
% http://tex.stackexchange.com/questions/49512/part-style-in-memoir-class/49534#49534
\renewcommand\partname{Part}
\renewcommand*{\partnamefont}{\normalfont\large} % part name
\renewcommand*{\partnumfont}{\normalfont\large} % part number
\renewcommand*{\parttitlefont}{\normalfont\LARGE} % part title
\renewcommand{\midpartskip}{\par\parbox{0.5in}{\hrulefill}\par}

\renewcommand{\beforepartskip}{\vspace*{\fill}}
\renewcommand{\afterpartskip}{\vspace*{\fill}}

% Set book title and the writer's name
% http://tex.stackexchange.com/questions/195863/include-document-title-in-memoir-class-header
% http://latex-community.org/forum/viewtopic.php?f=47&t=15857
\def\Booktitle{My book title goes here}
\title{\Booktitle}
\author{The writer's name}
\date{}

% Let's do it
\begin{document}

\frontmatter

% ENDORSEMENT
\pagestyle{empty}
\include{./include/00-prelims-pages/endorsement}
\cleardoublepage % Start a new odd page (manually)

% BOOK TITLE
\include{./include/00-prelims-pages/booktitle-01}
\cleardoublepage % Start a new odd page (manually)
\include{./include/00-prelims-pages/booktitle-02}

% BOOK INFO, ISBN, ETC
\include{./include/00-prelims-pages/kdt}

% DEDICATION
\include{./include/00-prelims-pages/dedication}

\pagestyle{My_pagestyle}

% FOREWORDS
\include{./include/00-prelims-pages/intro}
\cleardoublepage % Start a new odd page (manually)

% TOC
\tableofcontents

% SET PAGE NUMBERING (1, 2, 3.. for main content)
\mainmatter

% PROLOG
\include{./include/00-prelims-pages/prolog}

% PART 1
\part{This is Part}
\include{./include/part-01/01}
\include{./include/part-01/02}
\include{./include/part-01/03}
\include{./include/part-01/04}
\include{./include/part-01/05}
\include{./include/part-01/06}

% PART 2
\part{Part}
\include{./include/part-02/01}
\include{./include/part-02/02}
\include{./include/part-02/03}
\include{./include/part-02/04}
\include{./include/part-02/05}
\include{./include/part-02/06}
\include{./include/part-02/07}
\include{./include/part-02/08}
\include{./include/part-02/09}
\include{./include/part-02/10}
\include{./include/part-02/11}

% PART 3
\part{Part}
\include{./include/part-03/01}
\include{./include/part-03/02}
\include{./include/part-03/03}
\include{./include/part-03/04}

% ...and so on...

% ABOUT THE WRITER
\cleardoublepage % Start a new odd page (manually)
\pagestyle{plain}
\include{./include/about-writer}

% ...and so on...

\end{document}

A: Your minimal example only replicates problem (1), not (2). To solve (1), add
\renewcommand{\partnumberlinebox}[2]{#2 }
\renewcommand{\chapternumberlinebox}[2]{#2 }

to your preamble. It allows for a flexible spacing around the number for both \parts and \chapters, effectively discarding the requirement to place the part/chapter number inside a box of (fixed) width given by #1.

\documentclass{memoir}
\renewcommand\thepart{\arabic{part}}
\renewcommand{\partnumberlinebox}[2]{Part~#2 }
\renewcommand{\chapternumberlinebox}[2]{#2 }

% simulate larger part and chapter number
\setcounter{part}{50}
\setcounter{chapter}{1200}

\begin{document}

\tableofcontents

\part{This is My First Part}
\chapter{This is first chapter}
\chapter{This is very very long chapter title}
\chapter{Next chapter goes here}

\part{This is My Second Chapter}
\chapter{Very long chapter title also goes here}
\chapter{Another chapter goes here}
\chapter{Another chapter goes here}
\chapter{Another chapter goes here}

% ...and so on...

\end{document}

In the example above I've prepended each \part-like entry with Part~ as well.

A: Werner's answer seemed very authoritative, but when I tried it, I got the error

! LaTeX Error: \partnumberlinebox undefined.

Consulting the memoir manual suggested to me that the correct incantation was actually
\renewcommand\partnumberline[1]{#1\hspace{1em}}

and indeed that worked great for me! Here's my test case:
\documentclass{memoir}
% \renewcommand\partnumberlinebox[2]{#2\hspace{1em}}  % attempt 1, failed
% \renewcommand\partnumberline[1]{#1\hspace{1em}}     % attempt 2, worked

\begin{document}
\tableofcontents
\part{First}
\part{Second}
\part{Third}
\part{Fourth}
\end{document}

It appears that \partnumberline is supported at least as far back as memoir.cls version 2011/03/06 v3.6j (which is what I have), and \partnumberlinebox is a newer addition. I'm not sure why one would prefer one over the other.


text:
Q: How do I format a date on the iPhone to have this specific output? How do I format a date to produce the following output on the iPhone?
2010-09-24 13:00:00 -0700

A: Do you mean this code:
NSDate *date = [NSDate date];
NSLog(@"%@", date);


text:
Q: Do I Need a Workgroup File for Access 2007 Backend? I know I used to need these things when (once upon a time) I was an Access developer (Access 97), but do I need a workgroup file to share a backend database with two other users?
I did the split database thing and gave each their own copy of the front-end, and I thought that simply putting the backend part on a shared file location would do it.
The others can read the database and run forms and such, but they can't add rows - I still can.
What am I missing?


text:
Q: Keycloak: updating master realm via Admin API I tried to edit the master realm of my keycloak standalone installation via the admin api interface. I already created a whole realm and everything works fine. If I now try to update the client roles inside the master realm the server responds with "No content" but the data is not changed. What do I wrong?
relative url:
/auth/admin/realms/master/groups/654dc766-d307-4e44-9b6c-d53f16a2eedf
body:
{
"id":"654dc766-d307-4e44-9b6c-d53f16a2eedf",
"name":"TECHNICAL",
"path":"/TECHNICAL",
"attributes":null,
"realmRoles":null,
"clientRoles":{
    "test-client-realm":[
        "manage-realm",
        "manage-users",
        "view-realm",
        "view-users"
    ]
},
"subGroups":[]
}

A: updating client goes via PUT /admin/realms/{realm}/clients/{id} and not as stated in your question. In your example you would update a group.


text:
Q: MySQL syntax error; don't know where to begin I'm trying to create a table. I think the specifications of the table should be pretty obvious from the command I'm running:
create table users{
    id mediumint unsigned not null auto_increment,
    username varchar(40) not null,
    sprinkles bigint unsigned not null,
    passhash binary(64) not null,
    passsalt binary(64) not null,
    x decimal(10,1),
    y decimal(10,1),
    primary key (id),
    unique key idx_unique_username (username)
} engine = INNODB DEFAULT character set = utf8 COLLATE = utf8_general_ci;

However, when I try entering that into MySQL, it gives me this error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{
id mediumint unsigned not null auto_increment,
username varchar(40) not null,
' at line 1

My mysql version is Ver 14.14 Distrib 5.5.31, for debian-linux-gnu (x86_64) using readline 6.2

A: Begin with your parentheses shape.
Hint: find any create table example and compare to what you have
Hint 2: when mysql returns you a error about incorrect syntax - it points directly to the first token it couldn't parse. So your attention should be drawn to that exact character and some characters before it.

A: Switch out the { } brackets you have encapsulating your table information, replace them with ( ) parentheses, and you should be good to go.


text:
Q: switch DB before auth in laravel I am building an application, where there would be main application users (say support users) and separate client users (the application can have many different clients and each clients can have many users), every client has its own separate database, but the codebase for the entire application would be the same for every client.
What I wanted to achieve is, before calling auth in the main application, I wanted to call a middleware, which would detect a parameter (say db_slug) from request URL and according to that param it will change the DB respectively. And then login them to the client user to their respective DB.
Note: The client users will not be a part of the main DB. Their record would be only in their Client's DB.
But I am failing to do so, as my auth middleware is called first, before my custom middleware, and on accessing auth routes, it is saying unauthenticated, since that specific client user is not a part of my main application.
Note: I am using sanctum auth.
What I tried is, created a middleware called ClientDBMiddleware

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use DB;
use Config;

class ClientDBMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if($request->has('db_slug')){
            $dbSlug = $request->db_slug;
            DB::purge('mysql');
            Config::set('database.connections.mysql.database', "db_$dbSlug");
        }
        return $next($request);
    }
}

and applied it my api.php auth routes before auth middleware
Route::group(['middleware' => ['clientDB', 'auth:sanctum']], function () {
      Route::get('/me', [UserController::class, 'me']);
});

Important Note :
If there is a better approach to achieve my required thing, then that would be highly appreciated, please help me with it.


text:
Q: CMake target_link_libraries not linking shared library I have the following app being built and linked using CMake.
add_executable(my_node main.cpp)
target_link_libraries(my_node dynamic_lib my_dependency)

The source of my_node DOES NOT use dynamic_lib directly. my_dependency requires dynamic_lib to run.
Using readelf and ldd, I can see that dynamic_lib is not found on my_node; my app fails to launch. I can launch the app by instead setting LD_LIBRARY_PATH.
LD_LIBRARY_PATH="/path/to/dynamic_lib_dir" bash -c './my_node'

Alternatively, if I use classes from dynamic_lib in my_node source, it all works. I think I'm missing some CMake configuration here to force my_node to directly link with dynamic_lib. How can I bundle all of this up neatly?


text:
Q: Why $U^w=U \cap B_- w B_-$ is parametrized by $\mathbb R^m$? Let $G$ be a semisimple Lie group and $B_-$ a Borel subgroup of $G$. Let $U$ be a unipotent subgroup of $G$.
In the paper, Proposition 1.1, it is said that $U^w=U \cap B_- w B_-$ is parametrized by $\mathbb R^m$. That is, very element in $U^w$ can be written as $x_{i_1}(t_1) \cdots x_{i_m}(t_m)$, where $w=s_{i_1} \cdots s_{i_m}$ is a reduced expression.
I don't know how to prove that $U^w=U \cap B_- w B_-$ is parametrized by $\mathbb R^m$. Are there some examples in the case $G=GL_n$ which explain this result? Thank you very much.


text:
Q: What is the difference between these two ways of creating dynamo tables using terraform? I am new to terraform and reading about creating dynamo tables using terraform. I am coming across two different ways of creating dynamo tables.One is
resource "aws_dynamo_table" "table_name" {
   name         = "animal"
   billing_mode = "PROVISIONED"
   hash_key     = "key"
   attribute {
      name = "attrib1"
      type = "S"
   }
}

and the other way
module "dynamo_table_table_name" {
   source       = "terraform-aws-modules/dynamodb-table/aws"
   name         = "animal"
   billing_mode = "PROVISIONED"
   hash_key     = "key"
   attributes = [{
       name = "attrib1"
       type = "S"
   }]
}

What's the difference between them? Are they just different versions from the same provider (hashicorp/aws)? Which would be better way of doing it?


text:
Q: How to "change" published field sets in Meteor/mongo Does anyone know how to "change" field sets in a publication (Meteor.publish or Meteor.publishComposite) based on the certain characteristics/field values of the record with respect to the logged on user?
I was using a publishComposite, with cursors at the same level, like so:
Meteor.publishComposite("games", [
  {
    find: userRecord,
    children: [
      {
        find: gamesWeArePlaying
      }
    ]
  },
  {
    find: userRecord,
    children: [
      {
        find: gamesWeOwn
      }
    ]
  },
  {
    find: userRecord,
    children: [
      {
        find: examineWithAnalysis
      }
    ]
  },
  {
    find: userRecord,
    children: [
      {
        find: examineWithoutAnalysis
      }
    ]
  },
  {
    find: userRecord,
    children: [
      {
        find: allGames
      }
    ]
  }
]);

Each find function returns a cursor with qualifying records, and the field set allowed for that user in that state. Just be aware that in each of the children finds, it will find a set of unique records, but the fields it returns is specific to that cursor. The most common are transitions from "gamesWeArePlaying" to "examineWithAnalysis", and in the case of teacher/student, "examineWithAnalsyis" to "examineWithoutAnalysis."
But what is happening is that when a game (i.e. a single record) transitions from one cursor to another, the underlying framework fails to send correct "changed" fields to the client. The minimongo record(s) get all out of whack, and do not even match what's actually in the servers database.
So, my question is: What is the best way to return, reactively, a set of records, where every single record has a specific field set returned, based on characteristics of said record?

A: I read through your github code and it seems like your true intention here is to publish all games that this user should have "access" to and you want the user to have different permissions for each of the games. This is more of a mongodb solution, you want to have a normal publish(not composite, they are slow and don't work well) where you first get the user ID. Then just query for all the games (as you already are as a composite) like this
{
  $or : [
    { isolation_group : user.isolation_group }, // part of the user's isolation group
    { owner           : user._id }              // games we own
  ]
}

This should retrieve all the games the user should be privy to based on their isolation group or their ownership. I would suggest adding the isolation_group even to games you own in order to simplify the query - but that's optional. After you retrieve all these games you'll have them in an array, this is where a library like lodash comes to our help - you can do a series of _.map() calls like this
let gamesWeArePlaying = _.compact(_.map(ArrayOfAllGames, (game, key) => {
  if (game.status !== "playing" ||
        (game.white.id !== user._id && game.black.id !== user._id)) {
    return '';
  }

  return _.pick(game, [
    "black", "clocks", "fen", "lag", "observers", "pending",
    "rated", "rating_type", "startTime", "status", "tomove",
    "variations", "white", "wild"
  ]);
}));

Here is where it becomes a bit tricker, if you publish them as you mentioned with this.added/changed/removed to the same client side collection you are bound to get the same game, but you want to show it with specific fields based off of the results of the multiple _.map() calls. If you add the same game multiple times Meteor will publish the same game multiple times with the different permissions which is not what you want. So modify that map call to actually check for all permissions at once (i.e. gamesWeArePlaying, gamesWeOwn, examineWithAnalysis, ...) and change the _.pick() list of fields based on that. This will give you a unified array of games with proper fields to publish that will get updated reactively.

A: OK guys, I figured it out, and it was a stupid programmer error on my part. First, let me state that publishComposite, and changing fields, (alleged performance issues aside) does in fact work! Something like this does work:
publishComposite("publication", {
   find() {return collection1.find()},
   children: [
      {find(c1_record) {return collection2.find({s1},{fields: {f1: 1}})}}
      {find(c1_record) {return collection2.find({s2},{fields: {f1: 1, f2: 1}})}}
      {find(c1_record) {return collection2.find({s3},{fields: {f2: 1}})}}
   ]
});

No issues with this with Mongo, nor Meteor, nor DDP, nor the client, nor minimongo. It works great.
My problem is that you have to be REALLY REALLY careful when you use publishComposite when higher level finds are not meant for publication, but only for sub-qualifying records. Let's use my example. Above, I was publishing game records, and publishing certain fields based on certain states (if you were playing, if you could see computer analysis, etc.)
But, elsewhere, I have to publish chat records. In order to correctly publish chat records, I had to figure out what games a user was playing or observing. Whether they were playing or could see computer analysis was unimportant. I simply needed to know which games they were playing. So I did this:
publishComposite("chat", {
find() {
  return Meteor.users.find({_id:...})
},
children[
  {
    find() {return gamescollection.find({..all games user is involved with...})},
    children: [{
      find(){
        chat.find({...chats for game...})}
    }]
  }
]
});

See the problem?
The top level find publishes the user record, all fields in all its glory (possible problem #1!)
The second level find publishes the game record, all fields in all its glory. And that, my friends, was the problem. I simply did not put that together because I was not publishing the user nor the game on purpose, it was only for providing the requisite data for publishing the chat records at the the lowest level.
I changed this latter publication to return only the ID of the game records the user is involved with (i.e. gamescollection.find({...},{fields: {_id: 1}}), and just like that, everything worked.


text:
Q: How can I get PHPMailer working in my web server as it does in my local XAMPP server on my windows? I have a piece of PHPMailer code to send verification link to user's registered email upon completing registration. This code works exceptionally well on my local XAMPP server while I was developing my site. When I got done and deployed on my web server (hosted by namecheap), no email will be send when a user registers, while my database picks up and stores the user's details. I have searched for solution everywhere I can but couldn't find. Here is my piece of code (it still works fine on my XAMPP).
<?php

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\Exception;

require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';
        $mail = new PHPMailer;

        //Enable SMTP debugging.
        $mail->SMTPDebug = 2;
        //Set PHPMailer to use SMTP.
        $mail->isSMTP();
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        //Set SMTP host name
        $mail->Host = "smtp.gmail.com";
        //Set this to true if SMTP host requires authentication to send email
        $mail->SMTPAuth = true;
        //Provide username and password
        $mail->Username = "myusername@gmail.com";
        $mail->Password = "myemailpassword";
        //If SMTP requires TLS encryption then set it
        $mail->SMTPSecure = "tls";
        //Set TCP port to connect to
        $mail->Port = 587;

        $mail->From = "myemail";
        $mail->FromName = "myname";

        $mail->addAddress($email);

        $mail->isHTML(true);
        $mail->CharSet = 'UTF-8';

        $mail->Subject = "ACTIVATE YOUR ACCOUNT";
        $search  = array('[sponsor]', '[email]', '[uid]', '[code]', '[username]', '[phone]', '[password]', '[bankname]', '[accname]', '[accno]');
        $replace = array($sponsor, $email, $uid, $code, $username, $phone, $_POST['password'], $bankname, $accname, $accno);
        $mail->Body = str_replace($search, $replace, file_get_contents('../Emails/registeremail.html'));

        if(!$mail->send())
        {
            //add support link later
            $_SESSION['sign_msg']= "Something Went Wrong, Please contact Support";
            header('location:signup.php');
        }
        else
        {

        $_SESSION['sign_msg'] = "Verification link has been sent to your email.     ☑ <br>
        Click on the link to verify your account";
        header('location:signup.php');
            }
?>


text:
Q: Host aumu AudioUnit I'm having a heck of a time trying to get kAudioUnitEvent_ParameterValueChange to work with my custom C++ Audio Unit Host app and a third party 'aumu' unit.  I'm loading the unit and displaying the user interfaces just fine.  The audio unit is uniquely rare however, in that the plugin is an interface for an external hardware music device. I'm so close but getting weird results.
1) When I change a parameter on the external device, it shows the updated parameter value in the audio unit's custom UI but not in the generic UI. No event changes are notified.
2) When I change a parameter in the custom UI, neither the external hardware or generic UI detect the updated values and still no parameter change events.  So nothing was getting change values.
3) When I change a value in the generic UI, everything works properly.  I get updated parameter values on both the external device and the custom UI and I'm getting kAudioUnitEvent_ParameterValueChange events.
I'm ultimately trying to get the external device parameters to notify my host app of the event change. My understanding is that Audio Units automatically update parameter values between the UIs and should generate event changes no matter which UI end I use. It seems weird to me that it isn't all being handled automatically. Am I doing something wrong or could this have to do with the Plugin or my Host app?
It seems to work just fine using JUCE pluginHost example but I haven't been able to use JUCE's standalone modules in my project successfully either. Not a lot of Docs on the matter.  I've been at this for weeks and just out of ideas.


text:
Q: Is there a Logback summariser? Is there a summariser for java Logback that instead of repeating messages prints out "last message repeated 5000 times"?
I'm printing out the same database connection error 10 times a millisecond but have no control over the connection pool (quartz).

A: According to https://jira.qos.ch/browse/LOGBACK-803 at least, not a standard one. Since you're not the first one to want such, you might be able to find one from some other codebase. Happy hunting.


text:
Q: Split frames obtained from video into separate channels I am trying to read a video (mp4) frame by frame and then convert the frames from BGR to HSV.
I then want to split the HSV Mats into different channels (Hue, Saturation, Value).
this, however, does not work:
void colorize () {

VideoCapture cap("myFile.mp4");
Mat frame;
Mat frame2;

while (true) {
    cap>>frame;
    cvtColor(frame, frame2, CV_BGR2HSV);
    Vector<Mat> channels;
    split(frame2, channels);

   }
}

The split-function gives  the following error:
no matching function for call to 'split(cv::Mat&, cv::Vector<cv::Mat>&)'
     split(frame2, channels);

I have tried the exact same code outside of a loop with another image I had before transformed to hsv and it worked fine, so I assume the problem must be the looping.
Any ideas?

A: You're using cv::Vector, while instead you should use std::vector (note the lowercase v).
std::vector<Mat> channels; // std::vector, not cv::Vector
split(frame2, channels);


text:
Q: how to use C++ STL and boost to tell if two sorted vectors intersect I have two sorted C++ std::vector without duplicates (you could call them sets) and I want to know if they intersect. I do not need the vector of common elements.
I wrote the code at the end of this question using the boost::set_intersection algorithm in the boost "range" library (http://www.boost.org/doc/libs/1_50_0/libs/range/doc/html/range/reference/algorithms/set.html). This code avoids constructing the set of common elements but does scan all the elements of the vectors.
Is it possible to improve my function "intersects" using boost and the C++ STL without using a loop? I'd like to stop at the first common element in the vectors or at the very least avoid my counter class.
The boost range library provides "includes" and "set_intersection" but not "intersects". This makes me think that "intersects" is trivial or provided elsewhere but I cannot find it.
thanks!
#include <vector>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/function_output_iterator.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/algorithm_ext/erase.hpp>

template<typename T>
class counter
{
    size_t * _n;
public:
    counter(size_t * b) : _n(b) {}
    void operator()(const T & x) const
    {
        ++*_n;
    }
};

bool intersects(const std::vector<std::string> & a, const std::vector<std::string> & b)
{
    size_t found = 0;
    boost::set_intersection(a, b, boost::make_function_output_iterator(counter<std::string>(&found)));
    return found;
}

int main(int argc, char ** argv)
{
    namespace ba = boost::assign;
    using namespace std;
    vector<string> a = ba::list_of(string("b"))(string("vv"))(string("h"));
    vector<string> b = ba::list_of(string("z"))(string("h"))(string("aa"));
    boost::erase(a, boost::unique<boost::return_found_end>(boost::sort(a)));
    boost::erase(b, boost::unique<boost::return_found_end>(boost::sort(b)));
    cout << "does " << (intersects(a, b) ? "" : "not ") << "intersect\n";
    return 0;
}

A: Firstly to answer the comment, boost's set_intersection takes ranges as parameters compared to the STL one which takes iterators.
Other than that, there is no real difference with regards to the algorithm and the complexity.
As far as I know there is no ready-made library function to do what you want to do, which is just test if two sequences are unique and stop immediately if they are not.
You also have to realise that you will always have "worst case scenario" when they really are unique.
The complexity is O(N+M) although you can also use binary-search on one of the collections which will make it O(N log M) or O(M log N) and if one is a lot larger than the other this can be a big saving. (e.g. N=1000000, M=20, M log N is only approx 400)
You can "reduce" by taking the median of one, find it in the other and compare the sub-ranges in separate threads.
There is also the "horrible" solution of having your functor that gets called on an intersection throw, thus breaking you out of the loop. (Yes there is one there, even if it's hidden in an algorithm). We can probably write our own though that is O(N+M) very simply. I will do it with 4 iterators:
 template< typename Iter1, typename Iter2 >
 bool intersects( Iter1 iter1, Iter1 iter1End, Iter2 iter2, Iter2 iter2End )
 {
      while( iter1 != iter1End && iter2 != iter2End )
      {
         if( *iter1 < *iter2 )
         {
             ++iter1;
         }
         else if ( *iter2 < *iter1 )
         {
             ++iter2;
         }
         else
             return true;
      }
      return false;
 }

 // Predicate version where the compare version returns <0 >0 or 0

 template< typename Iter1, typename Iter2, typename Comp >
 bool intersects( Iter1 iter1, Iter1 iter1End, Iter2 iter2, Iter2 iter2End, Comp comp )
 {
      while( iter1 != iter1End && iter2 != iter2End )
      {
         int res = comp( *iter1, *iter2 );
         if( res < 0 )
         {
             ++iter1;
         }
         else if ( res > 0 )
         {
             ++iter2;
         }
         else
             return true;
      }
      return false;
 }


text:
Q: How can I install a third party MSI using a custom action? I have a Visual FoxPro installer (exe) that I want to launch using a WiX custom action. However, I think the VFP installer is a wrapper for an MSI as I'm getting "Error 1500" which seems to denote I'm trying to run two installers at the same time.
How can I bootstrap this third party MSI from my own MSI?
I'm currently launching the VFP installer in InstallExecuteSequence. I tried to run it in InstallUiSequence, but I'm calling my own installer from a ShellExec, so it doesn't run the InstallUiSequence.
Any pointers would be much appreciated.

A: It is technically infeasible with the current version of MSI. Installing your additional MSI via a bootstrapper is the recommended way.
Please see my answer to a related question here: Wix and .NET Framework (prerequisites)

A: You really can't and it would be a bad idea if you try to "work around" it.  If you really need this kind of functionality, use something like NISI to call the 3rd-party MSI and then call yours.

A: I've opened an MSI with Orca and saved it as a MSM (Merge Module) and added it to a Visual Studio setup project (not WiX sadly) before and it worked.
I'm pretty sure Orca comes with Visual Studio, but Google should give you good results to download it.
Give it a go in adding a MSM to your WiX project, and let us know what happens.


text:
Q: Programmatically Connect and Disconnect Android Device I need to find a way to (using an Android application) programmatically connect and disconnect an Android device from a host.
I am using a Galaxy Nexus. My goal is to keep everything as close to stock as possible, though I have already enabled verbose debug messages in the kernel and in order to view them have enabled root access on the phone to access /proc/kmsg (and the shell command dmesg).
I am certain that there is a way to leverage root access to do what I need to do, but all of my attempts have lead to nix.

*

*Mess with /proc/bus/usb

*Mess with /dev/bus/usb

*Change between MTP/PTP (unable to do programatically)

*Making the Android USB gadget driver into a module <- ???

I am going to try to figure out how to do the last object on the list, as then I would be able to rmmod and insmod the resulting *.ko in my application and that would connect and disconnect the phone. I am unsure of the feasibility of this option though.

A: Solution came when close to a deadline, so I am almost sure it is not the best way of doing things, but it met my requirements.
Build Modded kernel (to allow hooking of particular function)

*

*Modify kernel config to support Kprobes (set CONFIG_KPROBES to Y)

*Remove "static" keyword from android_setup() definition (driver/usb/gadget/android.c)

*Build that kernel

Build kernel module (which gives the actual functionality of connecting and disconnecting)

*

*Use Kallsyms to dynamically pull the absolute address of android_setup()

*Using kprobes, hook android_setup()

*Set up two timers to execute every time android_setup() is called

*First timer set for 2 seconds from now, Second set for 2.005 seconds from now

*Both timers take a pointer to the struct usb_gadget as their data

*In respective callback functions, call usb_gadget_connect() and usb_gadget_disconnect(), which forces physical disconnect followed by reconnect on the Samsung Galaxy Nexus

Build Application

*

*Gotta have a rooted device

*Simply make a shell call with SU privilege - "insmod module_name." Until you call rmmod, the module will force the device into an enumeration cycle, disconnecting and reconnecting continuously.

If you are interested in repeating these results, read the document posted here and feel free to send me any questions.
https://docs.google.com/uc?export=download&id=0B9WchRkSOWwJbi10MGhLWUljT2s

A: You can try to enable/disable some secured settings like Settings.Secure.USB_MASS_STORAGE_ENABLED or Settings.Secure.ADB_ENABLED (depending on what you call "connect" !)
This code should work (disabling USB mass storage):
Settings.Secure.putInt(getContentResolver(),Settings.Secure.USB_MASS_STORAGE_ENABLED, 0);

A: Settings.Secure.putInt(getContentResolver(),Settings.Secure.USB_MASS_STORAGE_ENABLED, 0);

A: InternetControl.java
public class InternetControl {
    public static void EnableInternet(Context context)
    {
        try {
            Log.i("Reached Enable", "I am here");
            setMobileDataEnabled(context,true);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public static void DisableInternet(Context context)
    {
        try {
            Log.i("Reached Disable", "I am here");
            setMobileDataEnabled(context,false);
        } catch (Exception e) {
    System.out.println(e.getMessage());
        }
    }

    private static void setMobileDataEnabled(Context context , boolean enabled) throws Exception{
           final ConnectivityManager conn = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
           final Class connClass = Class.forName(conman.getClass().getName());
           final Field iConnectivityManagerField = connClass.getDeclaredField("mService");
           iConnectivityManagerField.setAccessible(true);
           final Object iConnectivityManager = iConnectivityManagerField.get(conn);
           final Class iConnectivityManagerClass =  Class.forName(iConnectivityManager.getClass().getName());
           final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
           setMobileDataEnabledMethod.setAccessible(true);
           setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
        }

}

Manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET" />

Enable or Disable function are static so you can call by using
classname.functionname();


text:
Q: Python - CSV to extract data from text file into a CSV file I have a text file that is not completely formated, however it has column designated.
Code            Description          Unit          Retail
1000MADB90      Taupe 2X2            12X12         5.90
1002MOPAS       Grey Stilato         12X12         12.09

then some junk and then again
      Code            Description          Unit        Retail
    1050QADD         Black 2X2            12X12         2.12
    1002MOPAS       Red velvet            12X12         1.11

I need to be able to have it formated in a csv file and without the junk before and after. So, I would like to keep the column names and info after them until it hits junk and jumps into the other column that starts with Code. I have tried a few (12 to be precise) of examples found on stackeroverflow but cant seem to get it as it is formatted for the likes of Excel (csv). Also the columns in the text file vary in size and alignment (dunno if that matters)
I am no programmer but I am looking for an easy way to convert a catalog to input it in a POS System. I appreciate the help

A: An easy way to do it (provided you know an easy way to identify junk) :
with open('originalfile.csv','r') as f:
  with open('newfile.csv','w') as new_file:
    for row in f:
      if not is_junk(row):
        new_file.write(row)

def is_junk(row):
  return not row.strip() or ( not ( ("Retail" in row ) or is_float(row.split()[-1]) ) )

def is_float(str):
  try:
    float(str)
    return True
  except ValueError:
    return False


text:
Q: Error: Opening Robot Framework log failed If I open any .html file that generated by Robot Framework and try to convert it in any other format(for example, docx formate) using either any python code or inbuilt command line tool that are available. I am getting below error,

*

*Opening Robot Framework log failed

•          Verify that you have JavaScript enabled in your browser.
•          Make sure you are using a modern enough browser. Firefox 3.5, IE 8, or equivalent is required, newer browsers are recommended.
•          Check are there messages in your browser's JavaScript error log. Please report the problem if you suspect you have encountered a bug.
·      I am getting this error even though I have already enabled JavaScript in my browser.I am using Mozilla Firefox version 45.0.2 on mac.
Can anyone please help me to solve this issue?

A: I managed to make it work by editing the file /etc/sysconfig/jenkins and adding
-Dhudson.model.DirectoryBrowserSupport.CSP=
to the JENKINS_JAVA_OPTIONS setting. On my installation, the setting looks like
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true -Dhudson.model.DirectoryBrowserSupport.CSP= "

Then restart jenkins
service jenkins restart

Sources
https://wiki.jenkins-ci.org/display/JENKINS/Configuring+Content+Security+Policy
System properties management

A: We used to face same issue, however since we did not have access to jenkins, we could do it at client side be installing CSP plugin on chrome and enabling the plugin.

A: Running below code in Script Console of Manage Jenkins will work
System.setProperty("hudson.model.DirectoryBrowserSupport.CSP","sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;")

But whenever you start Jenkins then you have to execute this every time. Instead of this if you use this when you are starting Jenkins by using of batch file with below code then it will be better than this process
java -Dhudson.model.DirectoryBrowserSupport.CSP="sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;" -jar jenkins.war

A: Answer is explained at Jenkins issue tracking system: https://issues.jenkins-ci.org/browse/JENKINS-32118
To resolve your problem you must :

*

*Connect on your Jenkins URL (http://[IP]:8080/)

*Click on Manage Jenkins from left side panel.

*Click on Script Console

*Copy this into the field

System.setProperty("hudson.model.DirectoryBrowserSupport.CSP","sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;")

*Click on Run button.

*Execute your Jenkins build.

A: The easiest thing to do is (if there are no worries on security aspects) also a permanent fix.

*

*open the jenkins.xml file and

*add the following
<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -Dhudson.model.DirectoryBrowserSupport.CSP=""  -jar "%BASE%\jenkins.war" --  httpPort=8080 --webroot="%BASE%\war"</arguments>

*restart the jenkins server

*rerun your jenkins jobs to see the result files.
If we are using the script console, every time you restart the jenkins server, the changes will be lost.

A: The accepted answer works for me but is not persistent. To make it persistent, modify the file /etc/default/jenkins and after JAVA_ARGS line, add the following line:
JAVA_ARGS="$JAVA_ARGS -Dhudson.model.DirectoryBrowserSupport.CSP=\"sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;\""
Change will apply and be persistent after reboot

A: Please follow these steps to configure content security policies around Jenkins should resolve this issue:
1. Go to Jenkins
2. Click on Manage Jenkins
3.Click on Script Console
4.Enter unset header text shown in content security policies: System.setProperty("hudson.model.DirectoryBrowserSupport.CSP", "")
Click Run
The output should just show Result. If you see any thing other than this, that mean content policy is not updated successfully
If you are still facing the issue, please add the error details, what you tried, so we would be able to help you

A: The configuration change persists for me with Jenkins 2.235.2 installed via yum on CentOS 7 by placing the following content in a new file at $JENKINS_ROOT/init.groovy, changing ownership of the file to the jenkins user, and then restarting Jenkins with service jenkins restart
import jenkins.model.Jenkins;
System.setProperty("hudson.model.DirectoryBrowserSupport.CSP","sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;");

A: For me editing JAVA_ARGS in /etc/default/jenkins didn't work. To make changes permanent on Ubuntu 18.04 LTS when running Jenkins as service I did following:

*

*Run service jenkins status and from second line take path to actual service configuration file, mine was: /lib/systemd/system/jenkins.service

*Run sudo vim /lib/systemd/system/jenkins.service find property Environment= under comment Arguments for the Jenkins JVM

*Paste: -Dhudson.model.DirectoryBrowserSupport.CSP=\"sandbox allow-scripts; default-src 'none'; img-src 'self' data: ; style-src 'self' 'unsafe-inline' data: ; script-src 'self' 'unsafe-inline' 'unsafe-eval' ;\" behind -Djava.awt.headless=true

*Run sudo service jenkins stop, you should see following warning: Warning: The unit file, source configuration file or drop-ins of jenkins.service changed on disk. Run 'systemctl daemon-reload' to reload units.

*Run sudo systemctl daemon-reload

*Run sudo service jenkins start
You should be now able to browse robot framework results after restart.


text:
Q: Force mode working only on Y axis Unity3D I'm learning how to use Unity3D.
I have this scene where the elements are two PNG images (two black circles) to which I have associated the Rigidbody property (without gravity).

With a script I have associated the controller of the horizontal axis and it works: I can control the central circle with the keyboard.
Now I'm trying to associate a constant force. My script is as follows. But it only works along the Y axis. I can not make it work along the horizontal axis.
The script is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CircleController : MonoBehaviour {

    float MaxSpeed = 10f;
    Rigidbody rigid2D;
    public Vector3 tensor;

    // Use this for initialization
    void Start()
    {
        rigid2D = GetComponent<Rigidbody>();
        rigid2D.AddForce(new Vector3(0,10,0), ForceMode.Force);
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float move = Input.GetAxis("Horizontal");
        rigid2D.velocity = new Vector2(move * MaxSpeed, rigid2D.velocity.y);
    }
}

Can someone help me to understand why I can not put a force along that axis?
In particular, when I execute the script with this instruction: rigid2D.AddForce(new Vector3(0,10,0), ForceMode.Force);, I see the central circle moving towards the other. This is right.

Instead, when I execute it with this instruction rigid2D.AddForce(new Vector3(10,0,0), ForceMode.Force); the central circle remains stationary.

A: You call the following line in the Start function (executed once)
rigid2D.AddForce(new Vector3(10,0,0), ForceMode.Force);

It applies a force to the rigidbody to the right by the given value (10). The Physics engine computes the acceleration to apply to the rigidbody and will automatically compute the velocity (speed) and new positions each frame.
However, in the FixedUpdate, you call the following lines
float move = Input.GetAxis("Horizontal");
rigid2D.velocity = new Vector2(move * MaxSpeed, rigid2D.velocity.y);

Here, you force the velocity of the rigidbody on the horizontal axis, overriding the value computed by the Physics engine. If you don't press the buttons defined in the Input manager, the circle will remain still on the horizontal axis since move is equal to 0.

When calling rigid2D.AddForce(new Vector3(0,10,0), ForceMode.Force);, the circle moves up, because rigid2D.velocity = new Vector2(move * MaxSpeed, rigid2D.velocity.y); keeps the velocity on the vertical axis.


text:
Q: UserControl Within Template of another UserControl Loses values on postback This may be the really wrong way of doing this and so if it is please let me know!! I have a user control called ucDropDownList.ascx. It basically is a drop down with a button besides it. When the button is clicked a jquery dialog appears. The dialog is the problem. As this user control is used in a number of places i wanted (within the principles of OOP) to allow us to load in a different form depending on which drop down it was...So i went for Template User Control. The code behind for this is as follows:
public partial class ucDropDownList : System.Web.UI.UserControl

 {

   private ITemplate m_RecordForm = null;

   [TemplateContainer(typeof(cPopUpContainer))]
   [PersistenceMode(PersistenceMode.InnerProperty)]
   public ITemplate RecordForm
   {
     get { return m_RecordForm; }
     set { m_RecordForm = value; }
   }

   protected void Page_Load(object sender, EventArgs e)
   {

   }

   void Page_Init()
   {
     // Load in the Template control (we use this for making the different types of form!
     if (RecordForm != null)
     {
       cPopUpContainer container = new cPopUpContainer();
       m_RecordForm.InstantiateIn(container);
       phNewRecordForm.Controls.Add(container);
     }
   }

   public event EventHandler SaveClicked;
   protected void SaveButton_Clicked(object sender, EventArgs e)
   {
     if (SaveClicked != null)
       SaveClicked(this, e);
   }
 }

 public class cPopUpContainer: Control, INamingContainer
 {
   internal cPopUpContainer()
   {
   }
 }

Then i (will) have several user controls that are simple forms for each of the types that i will have these user controls for...(example given is a status table in the database). There is nothing exciting there, just that all of the controls have viewState Enabled. (pretty much as standard as it comes).
The page that i show these on has some markup like so...
<uc3:ucDropDownList ID="comboStatus" runat="server" OnSaveClicked="comboStatus_Saved">
                    <RecordForm>
                        <uc4:ucEdStatus ID="ucEdStatus1" runat="server" ViewStateMode="Enabled" />
                    </RecordForm>
                </uc3:ucDropDownList>

and a behind the scenes like so...
  protected void Page_Init(object sender, EventArgs e)
  {
     if (!IsPostBack)
    {
      ucEdStatus statForm = comboStatus.Controls[3].Controls[0].FindControl("ucEdStatus1") as ucEdStatus;
      statForm.InitializeControl(false);
    }
   }

  protected void Page_Load(object sender, EventArgs e)
  {

  }

  protected void comboStatus_Saved(object sender, EventArgs e)
  {
    ucEdStatus statForm = comboStatus.Controls[3].Controls[0].FindControl("ucEdStatus1") as ucEdStatus;
    statForm.SaveRecord(eSaveUCEdType.Insert);
  }

When the SaveRecord runs(this method is a simple insert into the database which is based on the values of the various controls on the ucEdStatus1 control) the controls on the ucEdStatus are all the default as set in the markup and non have maintained what the user put in (therefore the save just saves a wrong bit of data).
I am open to suggestions and criticism. If you need more information i can give it to you, i just need help in understanding why this is happening.
EDIT
Just in case you guys were wondering this is the class for the ucEdStatus control. It may answer why i am still scratching my head or may show how stupid i am.
long m_RecordID
{
  get { return (ViewState["recordid"] != null ? Convert.ToInt64(ViewState["recordid"]) : -1); }
  set { ViewState["recordid"] = value; }
}

bool m_isSupport
{
  get { return (ViewState["isSupport"] != null ? Convert.ToBoolean(ViewState["isSupport"]) : false); }
  set { ViewState["isSupport"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}

//--------------------------------------------------------------------------------
public void InitializeControl(bool aIsSupport)
{
  //Setup the issupport variable
  m_isSupport = aIsSupport;

  //Add the importance to the mixup...
  Array importanceTexts = System.Enum.GetNames(typeof(eStatusImportance));

  for (int i = 0; i <= importanceTexts.Length - 1; i++)
  {
    ListItem item = new ListItem(importanceTexts.GetValue(i).ToString(), i.ToString());
    comboImportance.Items.Add(item);
  }
}

//--------------------------------------------------------------------------------
public long SaveRecord(eSaveUCEdType aSaveType)
{
  using (cDBConnection con = new cDBConnection(this.Page, true))
  {
    cStatus stat = new cStatus(con.Con, m_RecordID);
    if (m_RecordID == -1)
      stat.Id = cGlobalDB.NewKey();

    stat.Importance = Convert.ToInt32(comboImportance.SelectedValue);
    stat.Name = txtName.Text;
    stat.Issupport = m_isSupport;
    stat.Color = edColor.Color;
    stat.SaveChanges((aSaveType == eSaveUCEdType.Insert ? eUpdateType.insert : eUpdateType.update));
    return (long)stat.Id;
  }
}

A: Try initializing that control in page_init every time; in other words, remove the !IsPostback check. All controls have to be initialized during page-init before their viewstate information will be applied. This is exactly equivalent as defining an asp.net control within aspx/ascx files (whatever is in those files goes through the same process, automatically for you done by asp.net).

A: So i found the answer after a little looking around.
This site really helped. The problem was the jquery modal pop up (dialog) was losing itself on post back. One line fix. How frustrating!


text:
Q: How to change the tax from 18% to 21% without changing prices I want to change the tax from 18% to 21% in my Prestashop. But I don't want to change the prices, I only want to show were it has to put 18%, the new IVA. For example, at the PDF invoice.
I changed all the strings for the 18% tax to "21 TAX" and it works at backend, but when, for example, PDF invoice seems to take the numeric value and I want to change that.
The file is classes/pdf.php
Any idea?
NEW: Code is too long, stackoverflow doesn't allow me to copy here the code. Here it is http://dl.dropbox.com/u/3915869/PDF.php

A: This sounds like the kind of thing that should be in a config file. I'm looking at line 666:
Configuration::get('PS_TAX')

Maybe change the value of PS_TAX in the config file?


text:
Q: Why can't you modify a collection in a for each loop How can you best explain why replacing an element of a collection you are looping using foreach is permited if you make a copy of it. Example:
foreach(Item item in Items)
{
   item.modify //or remove or add
}
// will not work

foreach(Item item in Items.ToList())
{
   item.modify //or remove. or add
}

//will work altough i dont get it because i am now iterating trough the temporary list
//and changing its elements.
//In my understanding its not like im iterating the list(.ToList) and modifying the source items
//(Items). A graphic representation would be welcome, my interest is to understand the
//matter logically

A: Because Enumerator relays on count of the elements in collection and you're not premitted to change it during the iteration.
If you make a copy of the list (responding to your question) you iterating over a copy of the collection you're changing. That is.

A: The Best answer would be that List has some kind of Tracking over its list items and can update its items as you ask but a simple IEnumerable does not so it will not allow you to change them.

A: What type is your Items?  What does the modify method do?  I could not reproduce what you could do with the second option.  I cannot compile this:
int[] nn = new int[] { 1, 2 };
foreach (var n in nn.ToList())
   n++;

Error: Cannot assign to 'n' because it is a 'foreach iteration variable'