text:
Q: Input 0 of layer conv3d_3 is incompatible with the layer: : expected min_ndim=5, found ndim=4. Full shape received: (None, None, None, None) My model structure is,
def build_deepunet(inputs, ker_init, dropout):
conv1 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(inputs)
conv1 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv1)

pool = MaxPooling3D(pool_size=(2, 2, 2))(conv1)
conv = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(pool)
conv = Conv3D(64, (2, 2, 2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv)
conv = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv)

pool1 = MaxPooling3D(pool_size=(2, 2, 2))(conv)
conv2 = Conv3D(32, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(pool1)
conv2 = Conv3D(64, (2, 2, 2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv2)
conv2 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv2)

pool2 = MaxPooling3D(pool_size=(2, 2, 2))(conv2)
conv3 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(pool2)
conv3 = Conv3D(64, (2, 2, 2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv3)
conv3 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv3)

pool4 = MaxPooling3D(pool_size=(2, 2, 2))(conv3)
conv5 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(pool4)
conv5 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv5)

up7 = Conv3D(64, (2,2,2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(UpSampling3D(size = (2,2,2))(conv5))
merge7 = concatenate([conv3,up7])
conv7 = Conv3D(32, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(merge7)
conv7 = Conv3D(64, (2, 2, 2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv7)
conv7 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv7)

up8 = Conv3D(64, (2,2,2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(UpSampling3D(size = (2,2,2))(conv7))
merge8 = concatenate([conv2,up8])
conv8 = Conv3D(32, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(merge8)
conv8 = Conv3D(64, (2, 2, 2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv8)
conv8 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv8)

up9 = Conv3D(64, (2,2,2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(UpSampling3D(size = (2,2,2))(conv8))
merge9 = concatenate([conv,up9])
conv9 = Conv3D(32, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(merge9)
conv9 = Conv3D(64, (2, 2, 2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv9)
conv9 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv9)

up10 = Conv3D(64, (2,2,2), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(UpSampling3D(size = (2,2,2))(conv9))
merge10 = concatenate([conv1,up10])
conv10 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(merge10)
conv10 = Conv3D(64, (3, 3, 3), activation = 'relu', padding = 'same', kernel_initializer = ker_init)(conv10)

conv11 = Conv3D(4, (1,1,1), activation = 'softmax')(conv10)

return Model(inputs = inputs, outputs = conv11)

input_layer = Input((IMG_SIZE, IMG_SIZE, IMG_SIZE, 3))

model2 = build_deepunet(input_layer, 'he_normal', 0.2)
model2.compile(loss="categorical_crossentropy",
optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), metrics =
['accuracy',tf.keras.metrics.MeanIoU(num_classes=4), dice_coef, precision, sensitivity,
specificity, dice_coef_necrotic, dice_coef_edema ,dice_coef_enhancing] )

and then, I tried to fit the model like this
K.clear_session()

history =  model2.fit(training_generator,
                 epochs=35,
                 steps_per_epoch=len(train_ids),
                 callbacks= callbacks,
                 validation_data = valid_generator
                 )
model2.save("model_x1_1.h5")

I got error:

ValueError: Input 0 of layer conv3d_3 is incompatible with the layer: : expected min_ndim=5, found ndim=4. Full shape received: (None, None, None, None)

How can I solve this problem?


text:
Q: Django rest framework browsable api root url I love DRF but I still find its documentation really frustrating, for real, a lot of advanced tips and examples are there but I still always dive into toughness and frustration when I'm looking for the most basic stuff of any topic of the amazing framework.
In this case, this resource
looks really cool! But they don't even start by how to make it work (or what could not be properly configured if it isn't working as in my case). Could someone tell me what's the holy api root URL or how to include/configure it? Because I don't see it in my URLs and so far I didn't find anything in the official docs.
I also followed the quickstart tutorial.
This is what I have:

My main urls.py:
api_urls = [
    path('rest_framework/', include('rest_framework.urls', namespace='rest_framework')),
    path('', include('project.posts.urls')),
    path('', include('project.users.urls')),
]

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(api_urls)),
]

users.urls:
router = SimpleRouter()
router.register(r'users', UserViewSet, basename='users')

urlpatterns = [
    path('', include(router.urls)),
]

posts.urls:
router = SimpleRouter()
router.register(r'posts', PostViewSet, basename='posts')

urlpatterns = [
    path('', include(router.urls)),
]

I can log in into the DRF panel but then I get a redirection error.

Also I can see the pages if I manually go to a valid endpoint URL, but it's not an actual navigation from the root point of the API.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intellisense doesn't work on one of c# projects in Visual Studio Code I wanted to open C# .Net Core project in Visual Studio, but unfortunately Intellisense doesn't seem to work properly, It highlights errors, but only when I build project. F12 (go to definition) doesn't work, as well as context specific suggestions.
What is strange: it works on other projects, but not this specific one.
C# Extensions I use in Visual Studio Code:
C# and C# extensions (I'm not sure which one enables intellisense)
There is an error in OmniSharp log:

[ERROR] Error: OmniSharp server load timed out. Use the 'omnisharp.projectLoadTimeout' setting to override the default delay (one minute).

But probably doesn't mean anything important.
I have currently .Net Core 1.1.0 installed, but project I want to open probably uses other version:
global.json
{
  "sdk": { "version": "1.0.0-preview2-1-003177" }
}

As far as I know, Intellisense should start working if project.json is available in folder. In my case: it is.
What could go wrong? What should I check to see why it doesn't work?

A: A while ago I had a similar problem, and I resolved that deleting the Project.sln, so you delete the configuration of your project, then you open this from project.csproj.
If it is not useful for you, you could try with the unsafe mode, open project properties, select Build tab and click on Allow unsafe code.


text:
Q: Bacon.js onValue() chain Why the construction like
$("#clickme").asEventStream('click').onValue(callback1).onValue(callback2);

doesn't work, but this one
var promise = $("#clickme").asEventStream('click');
promise.onValue(callback1);
promise.onValue(callback2);

works.
Doesn't the onValue method return reference to object? Is any purpose of that?

A: The onValue method returns a function for unsubscribing, hence is not chainable.


text:
Q: using BitmapData.draw() on a streaming (RTMP) .f4v with OSMF I am trying to use BitmapData.draw() on a video object, but using the OSMF framework.
My hosting service has set up the following so that I can access my rtmp video:
<VideoSampleAccess enabled="true">/</VideoSampleAccess>

Simplified code is as follows:
_videoURL = "my-url-here"
resource = new StreamingURLResource(_videoURL);
videoElement = new VideoElement(resource);
_player.media = videoElement;
container.addMediaElement(videoElement);
_player.autoPlay = true;
_player.play();

// later on, pause the player at the end
_player.pause();
// get the Video object
videoObj = _player.displayObject as Video;
// detach the netstream
videoObj.attachNetStream(null);

// get the bitmap from the Video object and draw on it..
bmpdata:BitmapData = new BitmapData(videoObj);

 bmpdata.draw()

However, I am getting the following error message:
SecurityError: Error #2135: Security sandbox violation: BitmapData.draw: ...

A: If you are streaming from Adobe Media Server the parameter needs to be set server side
http://www.shell-tips.com/2009/08/30/flash-how-to-fix-the-security-sandbox-violation-bitmapdata-draw/
I came across this when I attempted to create a reflection of the video stream under the video player.  Most CDN's will allow you to customize your media server application code... If not you need to change CDN's or switch to progressive playback

A: You could try drawing the container instead of the video object itself. The source for the draw method can be either of type Bitmap or DisplayObject , so any MovieClip or Sprite that adds your video should be drawable.
Edit:
You're right, wasn't really thinking ,if there's a security issue, drawing the container won't change much...
You could try this:

import flash.system.Security;

Security.loadPolicyFile('policyfileURL');


text:
Q: Updating outputs in PLCs For all PLC manufacturers, is Mass I/O copying the choice for updating outputs?
I found that there is another possible method: the continuous I/O updating.
Can anyone tell me what is the reason for this choice (Mass I/O copying)?
Are there any advantages over the continuous I/O updating method?

A: I had edited my response to your earlier question to cover this lightly. Here's some more detail for a basic PLC.
Task execution order
Typically PLCs task execution order runs as follows:

*

*Read the inputs.

*Execute the logic.

*Write the outputs.

*Handle other tasks, etc.

The 'Read the inputs' and 'Write the outputs' stages are the 'mass I/O copying' stages. The reason the logic is executed this way is that it presents a consistent state for the inputs through the program and prevents output strobing during the program scan. It also means that updating of I/O can be handled as a background task.
Problem with direct input read
  UP BUTTON               MOTOR UP
   X1                        Y0
--| |---------+-------------( )-

  UP BUTTON               MOTOR DOWN
   X1                        Y1
--|/|---------+-------------( )-

In the above example if X1 were to turn off between the first read and the second read both MOTOR UP and DOWN outputs would be energised simultaneously. Normal practice is to read all the inputs into an internal register and the program looks at that rather than directly at the inputs. This gives consistent predictable behaviour of the code and avoids race conditions.
Problem with direct output write
  UP BUTTON               MOTOR UP
   X1                        Y0
--| |---------+-------------(L)-

  UP LIMIT SW             MOTOR UP
   X2                        Y0
--| |---------+-------------(U)-

This example might not be the best code but PLC coding allows it and it can prove to be a useful tool when used with skips / jumps. The first rung turns on MOTOR UP using a latching 'relay coil'. The second rung unlatches the coil when the UP LIMIT SW turns on. It should be clear that if X1, UP BUTTON, switch is held on that immediate output writes would cause Y0 to blink briefly on every scan. Writing to the internal output memory and copying the whole lot to the outputs when program execution is complete solves this problem as the state at the end of the logic scan is what gets written to the outputs.
Immediate read
Most PLCs allow an immediate read and write which can be useful to shorten the cycle time of a machine. Others allow a few inputs to be used as interrupts so that program execution can jump to a subroutine and execute immediately.

A: Let we take into a consideration rack type PLC CPU where other peripheral IO devices are connected trough backplane bus. This bus usualy is a serial communiacation bus like CAN, I2C, RS485,...also the remote IOs can be connected trough a communication processor like DeviceNet, Canopen, Profibus, Modbus, etc... When you want to update the IO process image partition (this is the name of latched IO states in RAM) the CPU has to query R/W the IO module to get the updated value. For this reason it has no sense that at each IO evaluation in ladder program the CPU queries the peripheral IO for the last state - this takes quite long time. Also the ladder program would be inconsitent if at the beginning of the program the IO state is differing from the state in the middle or end of ladder program, this is an unwnated feature. Therefore the CPU first builds up the process image partition (sets outputs, reads inputs) then executes the ladder program.
The only exception is when the ladder program has to execute an time interrupt routine (like PID regulator), in that situation the CPU has to get IO data state at that moment, not a latched value from RAM, so it updates the required IO state (only the interested module, not the entire IO space).


text:
Q: Do asteroids create sonic boom while entering the atmosphere? Because of the lack of any materials to propagate sound, it can't spread in space. There's the air in the atmosphere, but its volume mass increases  constantly (either linear or exponential, I don't know) - it means that atmosphere doesn't have a sharp edge that separates it from space directly.
What happens, when an asteroid moves faster than the speed of sound (I suggest it happens quite often, but I'm not sure) and it enters to the atmosphere of Earth?
Does it create a sonic boom? Definitely, what's the level of atmospheric pressure that is necessary to the exist of sound (and consequently, sonic bangs) and how far is it from Earth surface?

A: According to the American Meteor Society, the sonic boom of an asteroid or meteor (sometimes referred to as a 'fireball') is due to

If a very bright fireball, usually greater than magnitude -8, penetrates to the stratosphere, below an altitude of about 50 km (30 miles), and explodes as a bolide, there is a chance that sonic booms may be heard on the ground below. This is more likely if the bolide occurs at an altitude angle of about 45 degrees or so for the observer, and is less likely if the bolide occurs overhead (although still possible) or near the horizon.

And from CalTech's CoolCosmos page

When an object travels faster than the speed of sound in Earth's atmosphere, a shock wave can be created that can be heard as a sonic boom.

The reason for asteroids causing sonic booms in the lower atmosphere, is according to the article How the Falling Meteor Packed a Sonic Punch (Klotz, 2013) is due to

Because the meteor is supersonic, the waves, which travel at the speed of sound, can't get out of the way fast enough. The waves build up, compress and eventually become a single shock wave moving at the speed of sound.

Looking a bit further in to what a sonic boom (Using a jet as an example) is and how it occurs is illustrated in the following diagram

Image source
So, if a meteor, asteroid is going faster than the speed of sound for  particular part of the atmosphere, then a sonic boom will occur.  Going back to the American Meteor Society's description of the likely cause of a sonic boom, they stated that if a meteor comes in

below an altitude of about 50 km (30 miles)

then a sonic boom is likely to occur, one of the reasons is that the speed of sound is slower, due to the temperature of the atmosphere at that height and lower.  Below is a graph showing the speed of sound plotted against temperature as a function of atmospheric elevation:

Image source.

A: I was looking this up to see how common sonic books from meteors uccur. I was on my roof two nights ago finishing up a project after dark. A light caught my eye. As soon as I looked up I herd a boom right as a meteor shot derectly over my head. It was a red and white streak from north to south. It was huge for a shooting star. The boom came from the direction of the meteor. I live in San Diego so if it made it through it probably hit Baja Mex or the Pacific. I for one can confirm meteors create sonic booms.


text:
Q: How to download gene expression data from NCBI gene database In the NCBI gene database, I can add the expression tracks (circled in picture blow) through 'Tracks' button, but How I can download the expression data directly, not just look the picture?

A: Have you tried Tools > Downloads then selecting the appropriate button that meets your needs?


text:
Q: Django how to upload CSV file using Form to populate postgres database and display all items in browser Django 3.2.1, Python 3.6, Postgres database
EDITED to take into account comments below, thanks!
I am writing a small Django app for storing product information. I coded the backend logic for uploading a local csv file using a Custom Management Command and am connecting this to the front end.
I am having trouble implementing the file upload -> having user upload products.csv via a Form submission to populate the database with file and display all products on one page.
I have stripped down my previous examples, as well as the suggested code below, to the simplest format to try to locate the problem.
Example of the csv file:
name,sku,description
Brian James,skus-look-like-this,The products will have various descriptions. And multiple lines too.

models.py
class Product(models.Model):
    name = models.CharField(max_length=500)
    sku = models.CharField(max_length=500)
    description = models.TextField(blank=False, null=False)
    status = models.TextField(blank=False, null=False, default='inactive')

    class Meta:
        db_table = 'product'

Form for individual product CRUD operations and for CSV file upload.
forms.py
class UploadForm(forms.Form):
    csv_file = forms.FileField(required=False, widget=forms.FileInput(attrs={'class': 'form-control', 'placeholder':
        'Upload "products.csv"', 'help_text': 'Choose a .csv file with products to enter'}))

/templates/upload.html
<form method="post" enctype="multipart/form-data">
        {% csrf_token %}
    <input type="file" name="sent_file" />
    <input type="submit" name="submit" value="Upload" />
</form>

views.py
# Function to upload the form, parse it, save to database
def create_upload(request):
    if request.method == 'GET':
        form = UploadForm()
        return render(request, 'upload.html', {'form': form})

    # If not GET method then proceed
    form = UploadForm(request.POST, request.FILES)
    print('FIRST FORM', form)

    # Validate the form
    if form.is_valid():
            csv_file = form.cleaned_data['csv_file']
            # Errors begin here ^, print(csv_file) = 'None'

            form.save()
            # Crashes here ^ with error: "AttributeError: 'UploadForm' object has no attribute 'save'
"
            file_path = os.path.join(BASE_DIR, form.csv_file.url)
            # printing `file_path` = `AttributeError: 'InMemoryUploadedFile' object has no attribute 'url'
`

            # read the file contents and save the product details
            with open(f'{file_path}, r') as products_csv:

            products_file = csv.reader(products_csv)
            next(products_file)  # skip header row

            for counter, line in enumerate(products_file):

                name = line[0]
                sku = line[1]
                description = line[2]

                p = Product()
                p.name = name
                p.sku = sku
                p.description = description
                p.status = random.choice(['active', 'inactive'])
                p.save()

    return redirect('/show_product')

Changing form.cleaned_data['csv_file'] to request.FILES['sent_file'] correctly prints the file name uploads.csv but the url is still inaccessible and still crashes on form.save(). The only way I can print to terminal the contents of the uploaded file is by adding this:
csv_file = request.FILES['sent_file']
for i in csv_file:
    print(i)

outputs:
b"'name','sku','description'\n"
b"'Zed','some-skus-more','descriptions. galore.'\n"

But the file still can't be uploaded and form.save() can't be implemented.
I'm not sure how to continue debugging this. If anyone can point me in the right direction, would really appreciate it!

A: In other to save CSV files you will create a function to read the csv file and save product details: but you can as well refactor the code to meet your suit.

*

*Upload and save the file first using Product()

*Get the path for the file and read the contents
It would be better if you have the same names for model fields and csv columns

*Loop through each line and create a dictionary which contains only a product details at an iteration

*Make an instance of Product() and pass the dictionary to it and save

*For the foreign key, get the object from Product() using get() accordingly with the value that is stored in csv

# You could save the Product details in two ways

new_product = Product()
new_product.registration_number = fields[0]
new_product.customer_name = fields[1] # Change this field name the customer
# like so for other fields

new_product.save()
.....
# Create a model object, create a dictionary of key values where keys corresponds to the field names of the model.

# create a dictionary `new_product_details` containing values of a product

new_product = Product()
new_product.__dict__.update(new_product_details)
new_product.save()

import csv
def save_new_product_from_csv(file_path):
    # do try catch accordingly
    # open csv file, read lines
    with open(file_path, 'r') as fp:
        products = csv.reader(fp, delimiter=',')
        row = 0
        for product in products:
            if row==0:
                headers = product
                row = row + 1
            else:
                # create a dictionary of product details
                new_product_details = {}
                for i in range(len(headers)):
                    new_product_details[headers[i]] = product[i]

                # for the foreign key field you should get the object first and reassign the value to the key
                #We will also have to change the product name to customer_name get the foreign key value
                new_product_details['customer_name'] = Product.objects.get() # get the record according to value which is stored in db and csv file

                # create an instance of product model
                new_product = Product()
                new_product.__dict__.update(new_product_details)
                new_product.save()
                row = row + 1
        fp.close()

Your code should look something like this after:
def uploadcsv(request):
    if request.method == 'GET':
        form = UploadForm()
        return render(request, 'upload.html', {'form':form})

    # If not GET method then proceed
    try:
        form = UploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            csv_file = form.cleaned_data['csv_file']
            if not csv_file.customer_name.endswith('.csv'):
                messages.error(request, 'File is not CSV type')
                return redirect('/show_product')
            # If file is too large
            if csv_file.multiple_chunks():
                messages.error(request, 'Uploaded file is too big (%.2f MB)' %(csv_file.size(1000*1000),))
                return redirect('/show_product')

            # save and upload file
            form.save()

            # get the path of the file saved in the server
            file_path = os.path.join(BASE_DIR, form.csv_file.url)

            # a function to read the file contents and save the product details
            save_new_product_from_csv(file_path)
            # do try catch if necessary

    except Exception as e:
        logging.getLogger('error_logger').error('Unable to upload file. ' + repr(e))
        messages.error(request, 'Unable to upload file. ' + repr(e))
    return redirect('/show_product')

Adding a customer name attribute to your model like so:
class Product(models.Model):
    customer_name = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    name = models.CharField(max_length=500)
    sku = models.CharField(max_length=500)
    description = models.TextField(blank=False, null=False)
    status = models.TextField(blank=False, null=False, default='inactive')

    class Meta:
        db_table = 'product'

A: Thanks to this SO post I was able to find an answer by using a generator to decode the CSV line by line.
Here is the code:
views.py
def decode_utf8(line_iterator):
    for line in line_iterator:
        yield line.decode('utf-8')

def create_upload(request):
    if request.method == 'GET':
        form = UploadForm()
        return render(request, 'upload.html', {'form': form})

    form = UploadForm(request.POST, request.FILES)

    # Validate the form
    if form.is_valid():

        # Get the correct type string instead of byte without reading full file into memory with a generator to decode line by line
        products_file = csv.reader(decode_utf8(request.FILES['sent_file']))
        next(products_file)  # Skip header row

        for counter, line in enumerate(products_file):
            name = line[0]
            sku = line[1]
            description = line[2]

            p = Product()
            p.name = name
            p.sku = sku
            p.description = description
            p.save()

        messages.success(request, 'Saved successfully!')

        return redirect('/show_product')


text:
Q: User Record Ownership - October CMS How I set or create that admin user can see only record which he created, or in which he is owner, like in this record this user is selected like owner.

A: you can do this by modifying your query like you can add one field for record which store user id and query can be as followings:
$record=DB::table('records')->where('user_id','=',auth()->user()->id)->get();

The above query only gives records which belongs to the logged in user.


text:
Q: Source Code fir Tiles struts-tiles2-1.4.0-SNAPSHOT I am not able to find the source code of struts-tiles2-1.4.0-SNAPSHOT.jar version of tiles.
The jar files are present at http://people.apache.org/~pbenedict/struts-osgi/org/apache/struts/struts-tiles2/1.4.0-SNAPSHOT/ location.

A: While choosing a Struts2 Tiles plugin, you must ensure it is the one designed for your version of Tiles (2 or 3), and it is the exact version of your Struts2 JAR (2.3.16, for example)
List for Tiles 2:

*

*Struts 2 Tiles 2 Plugin
List for Tiles 3:

*

*Struts 2 Tiles 3 Plugin

*

*(related : How to integrate Struts2 with Tiles 3)

*(related : Tiles 3 not Rendering List attributes)

The version 1.4.0 in your question it's not a valid Struts2 version, since Struts2 starts from 2.0.x, it is a Struts1 version: Struts1 Tiles2 plugin (the Struts2 tag in the question was misleading).

You can find the source code here.

Please remember that Struts1 is EOL.


text:
Q: TSconfig: compile a new js folder for each ts folder I want to compile a new js folder for each script folder. Is that possible with tsconfig.json?
Directories
folder1
  scripts
    index.ts

folder2
  scripts
   index.ts
tsconfig.json

Directories after compile
folder1
  scripts
    index.ts
  js
    index.js

folder2
  scripts
    index.ts
  js
    index.js
tsconfig.json

A: Disclaimer... this doesn't answer your question specifically, because what you want to do breaks with convention. Even if you manage to do it your way, I think you'll find the pain will outweigh the benefit.
The simplest way is to specify an outDir output directory. Your existing folder structure will be maintained in the output directory, with all the JavaScript and TypeScript kept cleanly separated.
{
    "compilerOptions": {
        "outDir": "./scripts",
        ...
    }
}

So if you start with:
/component-a
    index.ts
/component-b
    index.ts

You'll end up with the folders mirrored in the output directory.
/component-a
    index.ts
/component-b
    index.ts
/scripts
    /component-a
        index.js
    /component-b
        index.js

Unless you plan to deploy both (?) you don't normally want the TypeScript and JavaScript intermingled.


text:
Q: Action Script 3.0 Error 1105 : Target of assignment must be a reference value So, I have a frame containing two images and a paragraph text. I want to make only the two images zoomable by using the mouse scroll. But, for some reason the paragraphs are also zoomed in. I have tried to code it. Can you guys fix where it went wrong?
Error 1105 lies in the event.target.width(image1a) += zoomamountmlfr1;
var deltavarimage1amlfr1:int;
var deltavarimage2amlfr1:int;
var image1a : MovieClip = new MovieClip;
var image2a : MovieClip = new MovieClip;
var zoomamountmlfr1:int = 10;

addEventListener(MouseEvent.MOUSE_WHEEL, wheelimage1a2amlfr1);
function wheelimage1a2amlfr1(event:MouseEvent):void {
deltavarimage1amlfr1 = event.delta;
deltavarimage2amlfr1 = event.delta;
if (deltavarimage1amlfr1 > 0) {
    event.target.width(image1a) += zoomamountmlfr1;
    event.target.height(image1a) += zoomamountmlfr1;
}
else if(deltavarimage2amlfr1 > 0) {
    event.target.width(image2a) += zoomamountmlfr1;
    event.target.height(image2a) += zoomamountmlfr1;
}
else if(deltavarimage1amlfr1 < 0){
    event.target.width(image1a) -= zoomamountmlfr1;
    event.target.height(image1a) -= zoomamountmlfr1;
}
else if(deltavarimage2amlfr1 < 0){
    event.target.width(image2a) -= zoomamountmlfr1;
    event.target.height(image2a) -= zoomamountmlfr1;
}

}


text:
Q: How to handle browser level notification using Selenium Webdriver I am Automating some test cases using Selenium Webdriver and core Java,in chrome browser for one test case on clicking button I am getting browser level notification 'Show notifications with options Allow and Block'. I want to select Allow option. Can anyone know how to handle this kind of notifications using Selenium webdriver.
please refer following snapshot for more details

A: Please Follow below steps :
A) USING JAVA :

For Old Chrome Version (<50):

//Create a instance of ChromeOptions class
ChromeOptions options = new ChromeOptions();

//Add chrome switch to disable notification - "**--disable-notifications**"
options.addArguments("--disable-notifications");

//Set path for driver exe
System.setProperty("webdriver.chrome.driver","path/to/driver/exe");

//Pass ChromeOptions instance to ChromeDriver Constructor
WebDriver driver =new ChromeDriver(options);

For New Chrome Version (>50):

//Create a map to store  preferences
Map<String, Object> prefs = new HashMap<String, Object>();

//add key and value to map as follow to switch off browser notification
//Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);

//Create an instance of ChromeOptions
ChromeOptions options = new ChromeOptions();

// set ExperimentalOption - prefs
options.setExperimentalOption("prefs", prefs);

//Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);

For Firefox :

    WebDriver driver ;
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("permissions.default.desktop-notification", 1);
    DesiredCapabilities capabilities=DesiredCapabilities.firefox();
    capabilities.setCapability(FirefoxDriver.PROFILE, profile);
    driver = new FirefoxDriver(capabilities);
    driver.get("http://google.com");

B) USING PYTHON :
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

option = Options()

option.add_argument("--disable-infobars")
option.add_argument("start-maximized")
option.add_argument("--disable-extensions")

# Pass the argument 1 to allow and 2 to block
option.add_experimental_option("prefs", {
    "profile.default_content_setting_values.notifications": 1
})

driver = webdriver.Chrome(chrome_options=option, executable_path='path-of-
driver\chromedriver.exe')
driver.get('https://www.facebook.com')

C) USING C#:
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-notifications"); // to disable notification
IWebDriver driver = new ChromeDriver(options);

A: WebDriver driver ;
        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("permissions.default.desktop-notification", 1);
        DesiredCapabilities capabilities=DesiredCapabilities.firefox();
        capabilities.setCapability(FirefoxDriver.PROFILE, profile);
        driver = new FirefoxDriver(capabilities);
        driver.get("your Web site");

A: Steps to handle this type of requirements:

*

*Open Firefox Profile manager (Go to Start Menu, Type firefox.exe -p to launch profile manager)

*Create a new Profile (Ex. name of Profile is customfirefox)

*Navigate to about:permissions

*Do the required configurations and Save the Profile

Now use the newly created Profile to run your test by invoking the Firefox
ProfilesIni ffProfiles = new ProfilesIni();
FirefoxProfile profile = ffProfiles.getProfile("customfirefox");
WebDriver driver = new FirefoxDriver(profile);

This will always use the firefox with the custom configurations saved on the profile.
Hope this works for you..!!!
Good luck.

A: You can use below code to allow chrome to send notifications:
ChromeOptions options=new ChromeOptions();
Map<String, Object> prefs=new HashMap<String,Object>();
prefs.put("profile.default_content_setting_values.notifications", 1);
//1-Allow, 2-Block, 0-default
options.setExperimentalOption("prefs",prefs);
ChromeDriver driver=new ChromeDriver(options);

It works perfectly for me. Let me know if it doesn't work for you.
Cheers!!

A: As per my understanding,this pop-ups not javascripts one.So selenium won't handle them. Same kinda,authentication popup also there , which we automate via a hack like http://username:password@www.test.com , here giving user name and password in url itself.
In your case the way Praveen mentioned you have to create browser profile (FF or chrome ).In chrome, profile can be create  via desired cabilities options or chrome options function.

A: update:
Please use incognito mode to avoid such browser-level notifications and cookies issue.


text:
Q: Calling a function in a .as file from a nested movieclip I know there are lots of variations on this question but I can't find an answer that works for me.
Specifically I have some simple functions in a .as file. I've used #include and I can call the functions just fine from the main timeline, but I can't seem to call them from the timeline of nested movieclips.
I have a movieclip inside a movieclip inside a movieclip which is on the main timeline. How can I access the functions in the .as file?
I've tried this.parent.parent.parent.function() and _root.parent.parent.function() but neither works.
The functions are linked through Scaleform to a games engine so I'd rather not use classes as this will complicate things for me. For the same reason I'm using AS2, not AS3 (AS2 is not supported by the version of Scaleform included with the game engine).
Many thanks.

A: I think that you can simply use :
_root.your_function();

Or if your MovieClip is used directly in the main timeline :
this._parent.your_function();

And here don't forget that in AS2, we use _parent to get the parent of the current object.
You can get all the available included functions in the parent using this :
for(var element in this._parent){
    if(typeof this._parent[element] == 'function'){
        trace(element + ' : ' + this._parent[element]);
    }
}

Hope that can help.


text:
Q: SoapClient not working I have a php file in which a webservice is called with soapclient method.
This file works properly when i run it independently. But when it is called from another php file, following line leads php file to die and does not show any error.
$client = new SoapClient("http://x.x.x.x/x/Send?wsdl");

I have used try-catch to find out the error , but it does not show anythings and remaining codes are not executed.

$number     = $_GET['number'];
$msg        = $_GET['msg'];
$scode      = $_GET['scode'];
$id         = $_GET['id'];

if(!is_array($number)){
    $number = array($number);
}

if(!is_array($msg)){
    $msg = array($msg);
}

if(!is_array($scode)){
    $scode = array($scode);
}

if(!is_array($id)){
    $id = array($id);
}

$client = new SoapClient("http://x.x.x.x:xxx/x/Send?wsdl");

try{
$response = $client->function(
                    array(
                        'xxxxx'      => 'xx',
                        'xxxxx'      => 'xx',
                        'xxxxx'      => 'xx',
                        'xxxxx'      => xxx,
                        'xxxxx'      => $msg,
                        'xxxxx'      => $number,
                        'xxxxx'      => $scode,
                        'xxxxx'      => $id
                    ));
        return $response;
    }
    catch(Exception $e)
    {
        return $e->getMessage();
    }


text:
Q: Django - Get user with highest bid I need to get the user who placed the highest bid for the listing on an auction site.
models.py:
class Listing(models.Model):

class Category(models.TextChoices):
    BOOKS = 'Books'
    SPORTS = 'Sports'
    DEATHLY_HALLOWS = 'Deathly Hallows'
    CLOTHING = 'Clothing'
    WANDS = 'Wands'
    JEWELRY = 'Jewelry'

title = models.CharField(max_length=64)
description = models.TextField(max_length=320)
starting_bid = models.DecimalField(max_digits=10, decimal_places=2, default=0)
current_price = models.DecimalField(max_digits=10, decimal_places=2, default=0 )
img_url = models.URLField(blank=True)
category = models.CharField(choices=Category.choices, max_length=64, blank=True)
is_closed = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
winner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="Winner")

def __str__(self):
    return f"{self.title}"

class Bid(models.Model):
    listing = models.ForeignKey(Listing, on_delete=models.CASCADE, default=1)
    bid = models.DecimalField(max_digits=10, decimal_places=2)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="Bidder")

views.py:
def listing(request, listing_id):

highest_bid = Bid.objects.aggregate(Max('bid'))
winner = highest_bid.user

print(winner)

Returns the error: 'dict' object has no attribute 'user'.
How can I get the user from the maximum bid placed on the listing?

A: Order the Bids by the bid:
def listing(request, listing_id):
    highest_bid = Bid.objects.latest('bid')
    winner = highest_bid.user
    print(winner)
    # …


text:
Q: Enable Back button in azure ad b2c custom policies I have a multi step user journey in custom policy. I need to enable a back button to move back the previous step. Is this possible in AD B2C custom policy? Please help.

A: It is not possible to go back in the B2C user journey.
One method some people employed is a single SelfAsserted step, with all claims presented in the Technical Profile. But use JavaScript in your custom HTML to turn that into a multi page experience for the user, behind the scenes is a single page, and single submit.


text:
Q: Coordinate Point Drops on timeseries in QGIS I have timestamp data for every minute of a day (1140)for multiple objects by id, with a corresponding lat long. I want to get the time in which an id disappears off the map or off the csv. What would be the best tool, and is QGIS the best route?

A: If I understand you correctly, you're essentially looking for the largest timestamp value (the latest record) for each ID. You can accomplish this with a virtual layer and SQL query in QGIS:
Create a new virtual layer by going to Layer > Add Layer > Add/Edit Virtual Layer.

Hit the Import button to add a layer that is already in your map, and then modify that example SQL query so it is selecting from the Local Name of the layer you just imported.


text:
Q: On initial load page transition snaps So when the page first loads and the user enters input the progress bar "snaps" to the first location, rather ease in like the others. I'm not sure what I'm doing wrong. Here's my css
 .top {
background: #009dff;
position: fixed;
z-index: 1031;
bottom: 0;
left: 0;
transition:all 1s;
height:54px;
}

And here's a fiddle. Press run then enter an input.Ideas?

A: This is because you have not given it a default width, and therefore it is defaulting to auto. auto is not a value that can be animated, therefore it snaps the first time you give it value.
Try adding width: 0 to your CSS.


text:
Q: ArcGIS initial map location jsapi I am trying to use a customers ArcGIS system to render a map on a page using the ArcGIS Javascript API.
To define a map in examples it displays:
map = new Map("map",{
          basemap: "topo",
          center: [-117.19,34.05], // lon, lat
          zoom: 13
        });

however this is showing fixed co-ordinates.
I want to be able to hit the RESTAPI in the customers internal system with a land id and return and plot the co-ordinates.
Currently I am retrieving a Degree Minute Second latitude and longitude from the land but wondering if there is a simpler way then having to get these values as a string, split them into degrees minutes seconds and then making a calculation to get their X,Y values to plot into this function to define a map.
Essentially I am just trying to load a map in a location specified by the land id and then after load map layers on top, all through the the local systems RestAPI and the Javascript API.
Thanks,

A: This is all about spatial reference(i.e 102100, 4326 etc) of the map.
Whatever you will add above snippet code this will add a map with basemap (topology) and center of the map will be co-ordinates which you have provided.
if you want to add a point to map and it has different format of geometry then  you can use project geometry operation to convert.
require([
  "esri/tasks/ProjectParameters", ...
], function(ProjectParameters, ... ) {
  var params = new ProjectParameters();
  params.geometries = [point];
  params.outSR = outSR;
  params.transformation = transformation;
  gsvc.project(params);
  ...
});

For Reference: https://developers.arcgis.com/javascript/jsapi/geometryservice-amd.html#project
Convert Degree minute second to decimal/Lat long:
function ConvertDegreeAngleToDecimal(degrees, minutes, seconds )
{
    //Decimal degrees =
    //   whole number of degrees,
    //   plus minutes divided by 60,
    //   plus seconds divided by 3600

    return degrees + (minutes/60) + (seconds/3600);
}

Hope this will help you.
Let me know if you need more clarifications!


text:
Q: "Must have" Visual Studio addons So - this is a question to all the Visual Studio users out there - what addons do you use, and can't live without - and why ?

A: *

*Resharper or devexpress refactor (pro or express )

*.NET Reflector

*AnkhSvn

*Microsoft StyleCop

A: VisualSVN if you're using Subversion. It works amazingly well, and it doesn't mess with Visual Studio's brain-damaged source control bindings.

A: I use VisualSVN but I heard since v2.0 AnkhSVN is pretty solid, personally for $49 dollars it is a solution I already bought into and has always been stable.
Resharper is a must.
Aside from those two VS2008 provides everything I need. On VS2005 I use CoolCommands to get some things like 'Open Folder in Explorer' from solution explorer too.
I forget... I use Test-Driven.Net plugin to get the right click 'Reflector' and test coverage with NCoverExplorer for the rare times I use it, and the even more rare times when JetBrains implementation of NUnit via their Test runner doesnt work.

A: Just one: ReSharper!
Can't live without it.

A: First and foremost: CodeRush - absolutely the best and greatest addon there is - even in a FREE FOR ALL version (CodeRush Xpress).
Next:  PowerCommands for Visual Studio 2008 - free as well
Others: Only for specific topics, e.g. VisualSVN for Subversion access etc.
Marc

A: Visual Assist X - Whole Tomato

A: I don't use any addons. VS is good enough.

A: I knew someone would beat me to R#, without a doubt the best productivity add-on.
Other than that, AnkhSVN as an SVN client and that's pretty much it. IMHO VS2008 is an excellent IDE that doesn't need to many add-ons.

A: Not an addon but it's manually installed like an addon and overlooked by a lot of developers: SP1 for VS2008. Finally adds background compilation! Also greatly improved Javascript editing.

A: These tool are very useful

*

*Outliner Power Toy

*Power Commands


text:
Q: Finite state machine boolean expression I'm looking at this mealy machine:

and this state table with the boolean expressions at the bottom.

If you look at the \$S_1\$ boolean expression, it says \$S_1 = \overline S_1 S_0 B + S_1 A B\ \$.
Shouldn't it be \$S_1 = \overline S_1 S_0 B + S_1 \overline S_0 A B\ \$?
Why did they miss out the \$\overline S_0\$?

A: Actually, when you see the state representation of the FSM, you shall notice that the output is \$1\$ when both the inputs \$A\$ and \$B\$ are \$1\$ and the machine is in state \$S_2\$ which is represented by the encoding \$10\$. So, it is enough to represent the output as \begin{equation}q = S_1 AB\end{equation}. The reason that the \$ \bar{S_0}\$ is not included in the expression \begin{equation} S_1'=\bar{S_1}S_0 B+S_1 AB\end{equation} is that there is no state defined by the encoding \$11\$ and hence the state \$10\$ is actually \$1X\$ and hence it is sufficient to include just \$S_1\$.


text:
Q: SQL Sequence column with condition I need to add new column to my SQL Query so i can sort the results afterwards by some ID (integer) and not by name (string).
The problem is I want to make sure that some of the names to be with highest SequenceID so i can put them at the end.
I came up with something like this:
ROW_NUMBER() OVER(ORDER BY IIF([Name] = N'something', 'zzzzSomething', [Name]) ASC) AS SequenceID

Any better implementation?

A: Sort first by special name or not and then by name:
ROW_NUMBER() OVER (ORDER BY
                    case name when N'John' then 3 when N'Mary' then 2 else 1 end, name
                  ) AS SequenceID

This sorts 'John' last, and before that 'Mary', and before that all other names in alphabetic order.


text:
Q: Reloading an object not working in rspec I am trying to test a controller method with the following code:
it "should set an approved_at date and email the campaign's client" do
  @campaign = Campaign.create(valid_attributes)

  post :approve, id: @campaign.id.to_s

  @campaign.reload
  @campaign.approved_at.should_not be(nil)
end

However, when I run this test, I get the following error:
 Failure/Error: @campaign.reload
 ActiveRecord::RecordNotFound:
   Couldn't find Campaign without an ID

When I run the analagous lines in the rails console, the reload works and the value is set as I need it to be.  Why isn't reload working for me when I run the code in an rspec test?

A: Two possible places for errors.

*

*object creation. i.e.@campaign = Campaign.create(valid_attributes) Your object may not be created correctly. I suggest you to use create! instead of create in the test so that any error will be thrown.

*Controller. When controller expect to find the object with an integer id, you feed it a string. That may also be the problem. I suggest you not to convert the id into string. If for GET, you can do that though not necessary. If for POST, converting to string is wrong.

A: I would run a test to ensure a Campaign record is actually being created:
@campaign = Campaign.create(valid_attributes)
puts @campaign.id

.reload is the first place in your code that a nil @campaign would flag an error (since you can call .to_s on a nil object)

A: I solved the problem by switching to FactoryGirl:
  @campaign = FactoryGirl.create(:pending_approval_campaign)
  @campaign.approved_at.should be(nil)

  post :approve, id: @campaign.id.to_s

  @campaign.reload
  @campaign.approved_at.should_not be(nil)

That works as intended


text:
Q: How do we balance the chemical equation and give an integer solution? $$\require{mhchem}\ce{NaOH + H2SO4 -> Na2SO4 + H2O}$$
I'm trying all my best to come up with one solution but cant.
in giving the integer solution to this chemical equation is it compulsory?

A: Denote the numbers on the left with $a$ and $b$ and on the right with $c$ and $d$.
This leads to the system
$$a=2c$$
 $$b=c$$
 $$a+2b=2d$$
 $$a+4b=4c+d$$
considering the number of Na,S,H and O-atoms.
This can also be written as
$\pmatrix {1&0&-2&0\\0&1&-1&0\\1&2&0&-2\\1&4&-4&-1} \pmatrix{a\\b\\c\\d}=\pmatrix{0\\0\\0\\0}$
The kernel of the matrix is $t\pmatrix{2\\1\\1\\2}$, so $(2,1,1,2)$ is the solution.
An easier way to solve the system is to simply start with $b=1$. Then you easily
 get the solution. If fractions would occur, this would also be no problem because
 any multiple of a solution is again a solution.


text:
Q: Converting hex to binary How can I Convert these binary input into hex values. Using python 3:
11111000 10011011

01101101 10011101

11100001 01111011

11000001 00010111

A: In your case you can do something like:
a = "11111000 10011011 01101101 10011101 11100001 01111011 11000001 00010111"
a = a.replace(" ", "")
i = int(a, 2)
print(hex(i))

A one-liner would be:
print(hex(int("11111000 10011011 01101101 10011101 11100001 01111011 11000001 00010111".replace(" ", ""), 2)))


text:
Q: Suppress an Exception but Continue after the Exception, not after the Suppression Assume the following minimal example:
def external_code():
    for i in range(10):
        if i == 7:
            raise ValueError("I don't like sevens.")
        print(i)

external_code()

When suppressing the exception either through handling it
try:
    external_code()
except ValueError:
    pass

or by suppression through contextlib.suppress()
from contextlib import suppress

with suppress(ValueError):
    external_code()

the exception will not be raised, but the execution of the code after it will be prevented, and instead continue in the except block or after the suppression.
Is it possible to suppress an Exception and then continue with the external code, as if the Exception would not even be there? In the code examples above, this would cause all 10 numbers to be printed, instead of only 0 to 6.
I need this, because an external library (TensorFlow) raises an exception it should not raise. Related to the minimal example from above, this means that I cannot edit the code in the function, I can only put code around its call. I can comment out the exception in TensorFlow, but that's tedious with updating TF and would also cause the exception to not occur in other cases where it is actually appropriate.

A: As a workaround you could redefine the method at any time:
class SomeTensorFlowClass(object):
    def that_method(self, n=10):
        for i in range(n):
            if i == 7:
                raise ValueError()
            print(i)

stf = SomeTensorFlowClass()

def that_method(n=10):
    self = stf  # for non-static methods
    for i in range(n):
        print(i)

stf.that_method = that_method

This way, you still "update" TensorFlow, but you can undo it directly after the situation.
If you switch often, you can add a new flag like seven_is_ok=False to skip the Exception conditionally.
If you want to avoid copying library source code, you can retrieve it from the live object with inspect.getsource(stf.that_method) followed by the desired replacements and exec("global that_method\n" + adapted_source_code). Be aware that indentation changes and forgotten imports may only mark the beginning of potentially many troubles with the inspect-based workaround.
Clearly, none of that is as beautiful as patching the library, but I assume you have reasons for not doing that now.


text:
Q: Toy model for entangling interaction? Most of the time entanglement is described using some instantaneous classical measurement from an apparatus, but it is possible to describe it between two quantum systems, with two systems $O$ (for the observer) and $S$ undergoing the following process
$$\vert \psi^O \rangle \otimes\vert \psi^S \rangle \to \sum_\alpha a_\alpha  \vert \psi^O_\alpha \rangle \otimes \vert \phi_\alpha \rangle$$
for a bunch of measurement with value $\alpha$ and probability $a_\alpha^2$.
But is there a toy model to show this process actually happening, where two particles, originally just a tensor product of the free states, evolve into entangled states, ideally without using some instantaneous interaction like a quantum gate? Also does this conflict with the fact that for long range interactions, particles are always interacting with each other?

A: Assume that $\left| \psi^O \right. \rangle$, $\left| \psi^S \right. \rangle$ are just two spin 1/2 particles. Then a Heisenberg interaction:
$$\vec{S^o} \cdot \vec{S^s} = \hat{S_x^o} \otimes \hat{S_x^s} + \hat{S_y^o} \otimes \hat{S_y^s} + \hat{S_z^o} \otimes \hat{S_z^s}$$
will evolve a product state into an entangled singlet state:
$$\frac{1}{\sqrt{2}} \left( \left| \uparrow^O \right. \rangle \left| \downarrow^S \right. \rangle - \left| \downarrow^O \right. \rangle \left| \uparrow^S \right. \rangle \right)$$
It is possible to generalize this to a more realistic "observer" and "system". A simple way of playing around with this is to numerically generate a random hermitian $(NM \times NM$) matrix, where $N = dim(system)$, $M=dim(observer)$. Diagonalize the matrix and find the lowest energy eigenvector. Reshape this $NM$-vector into a $(N,M)$ matrix and do a singular value decomposition of it. The entanglement entropy can then be found from the singular values $\Lambda_i$ as
$$S = \sum_i -\Lambda^2_i \log(\Lambda^2_i)$$
You will find that most Hamiltonians have an entangled ground state. This would mean that your initial product state (with sufficient overlap) would also evolve to such an entangled state.
More realistic would be to include the effect of an environment by using the theory of open quantum systems. In "most cases" the environment destroys the entanglement, which is an explanation why quantum entanglement is so fragile. See https://arxiv.org/pdf/quant-ph/0306072.pdf for more on the subject.
Maybe this at least answers the first part of your question.


text:
Q: hadoop - total line of input files I have an input file contains:
id   value
1e   1
2e   1
...
2e   1
3e   1
4e   1

And I would like to find the total id of my input file. So In my main, I have declare a list so that when I read the input file, I will insert the line into the list
MainDriver.java
public static Set list = new HashSet();
and I my map
// Apply regex to find the id
...

// Insert id to the list
MainDriver.list.add(regex.group(1));    // add 1e, 2e, 3e ...

and In my reduce, I try to use the list as
 public void reduce(WritableComparable key, Iterator values,
            OutputCollector output, Reporter reporter) throws IOException
    {
        ...
        output.collect(key, new IntWritable(MainDriver.list.size()));
    }

So I expect the value print out the file, in this case will be 4. But it actually prints out 0.
I have verify that regex.group(1) would extract valid id. So I have no clue why the size of my list is 0 in the reduce process.

A: The mappers and reducers run on separate JVMs (and often separate machines altogether) both from each other and from the driver program, so there is no common instance of your list Set variable that all of those methods can concurrently read and write to.
One way in MapReduce to count the number of keys is:

*

*Emit (id, 1) from your mapper

*(optionally) Sum the 1s for each mapper using a combiner to minimize network and reducer I/O

*In the reducer:

*

*In setup() initialize a class-scope numeric variable (int or long presumbly) to 0

*In reduce() increment the counter, and ignore the values

*In cleanup() emit the counter value now that all keys have been processed

*Run the job with a single reducer, so all the keys go to the same JVM where a single count can be made

A: This is basically ignoring the advantage of using MapReduce in the first place.
Correct me if I'm wrong, but it appears you can map your output from your Mapper by "id", and then in your Reducer you receive something like Text key, Iterator values as the parameters.
You can then just sum up values and output output.collect(key, <total value>);
Example (apologies for using Context rather than OutputCollector, but the logic is the same):
 public static class MyMapper extends Mapper<LongWritable, Text, Text, Text> {

    private final Text key = new Text("id");
    private final Text id = new Text();

    public void map(LongWritable key, Text value,
                    Context context) throws IOException, InterruptedException {
         id.set(regex.group(1)); // do whatever you do
         context.write(id, countOne);
    }

}

public static class MyReducer extends Reducer<Text, Text, Text, IntWritable> {

    private final IntWritable totalCount = new IntWritable();

    public void reduce(Text key, Iterable<Text> values,
                       Context context) throws IOException, InterruptedException {

        int cnt = 0;
        for (Text value : values) {
            cnt ++;
        }

        totalCount.set(cnt);
        context.write(key, totalCount);
    }

}


text:
Q: Short circuit detector (autoreverser circuit) using current sensor and switching relay First of all I'm not electrical engineer. The original idea is described here.
It is a model railroad problem. The rails are carrying a power signal (DCC) 12-18 V. The frequency is ~17 kHz. It is a square wave signal described here.
The circuit swaps the hi and low rails when the short occurs. This it happens at the gap between two insulated parts of the rail track with the hi and low rails not corresponding. When the train wheel bridges the two unmatched rails we have a short. The reverser has to detect this at a lower level of the boosters  amper limit  and switch the signal to the rails of the reverse section.
In the original circuit, I replaced the shunt with an ACS712 current detector. I replaced the other parts in the circuit with parts that are available in Ltspice to simulate it. The original circuit checks and the second gap. In my scheme is only the detector for one gap.

*

*Will this circuit work?

*Is the ACS712 sensor a good replacement?

*What are the suitable DIP components?

*Can I "catch" the output from the 555 with an Arduino and switch the relay?

I have and other thoughts like set the comparator's limits with a potentiometer or from Arduino.
I hope the comments in the LTspice schematic will help. Any thoughts and critique are welcome. I didn't find a way to attach the LTspice file.

A:
Will this circuit work?

Do you have any reason to doubt the simulation? Looks fine to me.

Is the acs712 sensor a good replacement?

Sure. The bandwidth is adequate. You just need to pick the correct sensitivity range for your application. (5A, 20A, 30A)

What are the suitable DIP components?

We don't do product recommendations here. But your favorite distributor's website (Digi-Key, Mouser, etc.) will be able to help you there.

Can I "catch" the output from the 555 with an Arduino and switch the relay?

Sure, no problem.

I have and other thoughts like set the comparator's limits with a potentiometer or from Arduino.

Also no problem.
But if you're going to throw a microcontroller in there anyway, you can simplify the circuit considerably, eliminating the comparators, the 555 and the DFF. Just digitize the output of the current sensor directly (ADC with an adequate sample rate), do all of the logic in firmware, and switch the relay driver as needed.


text:
Q: Doctrine doesn't load associations from session correctly I'm having this behavior with Doctrine 2.1 where I'm looking for a nice 'workaround'. The problem is as follows:
I have a user Entity:
/**
 * @Entity(repositoryClass="Application\Entity\Repository\UserRepository")
 * @HasLifecycleCallbacks
 */
class User extends AbstractEntity
{
    /**
     *
     * @var integer
     *
     * @Column(type="integer",nullable=false)
     * @Id
     * @GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     *
     * @var \DateTime
     * @Column(type="datetime",nullable=false)
     */
    protected $insertDate;

    /**
     *
     * @var string
     * @Column(type="string", nullable=false)
     */
    protected $username;

    /**
     *
     * @ManyToOne(targetEntity="UserGroup", cascade={"merge"})
     */
    protected $userGroup;
}

And a usergroup entity:
/**
 * @Entity
 */
class UserGroup extends AbstractEntity
{
    /**
     *
     * @var integer
     *
     * @Column(type="integer",nullable=false)
     * @Id
     * @GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     *
     * @var string
     * @Column(type="string",nullable=false)
     */
    protected $name;
}

If I instantiate a user object (doing this with Zend_Auth) and Zend_Auth puts it automatically the session.
The problem is however, that is I pull it back from the session at a next page then the data in the user class is perfectly loaded but not in the userGroup association. If I add cascade={"merge"} into the annotation in the user object the userGroup object IS loaded but the data is empty. If you dump something like:
$user->userGroup->name
You will get NULL back. The problem is no data of the usergroup entity is accesed before the user object is saved in the session so a empty initialized object will be returned. If I do something like:
echo $user->userGroup->name;

Before I store the user object in the session all data of the assocication userGroup is succesfully saved and won't return NULL on the next page if I try to access the $user->userGroup->name variable.
Is there a simple way to fix this? Can I manually load the userGroup object/association with a lifecycle callback @onLoad in the user class maybe? Any suggestions?

A: Your problem is a combination of what mjh_ca answered and a problem with your AbstractEntity implementation.
Since you show that you access entity fields in this fashion:
$user->userGroup->name;

I assume your AbstractEntity base class is using __get() and __set() magic methods instead of proper getters and setters:
function getUserGroup()
{
    return $this->userGroup;
}

function setUserGroup(UserGroup $userGroup)
{
    $this->userGroup = $userGroup;
}

You are essentially breaking lazy loading:

"... whenever you access a public property of a proxy object that hasn't been initialized yet the return value will be null. Doctrine cannot hook into this process and magically make the entity lazy load."

Source: Doctrine Best Practices: Don't Use Public Properties on Entities
You should instead be accessing fields this way:
$user->getUserGroup()->getName();

The second part of your problem is exactly as mjh_ca wrote - Zend_Auth detaches your entity from the entity manager when it serializes it for storage in the session. Setting cascade={"merge"} on your association will not work because it is the actual entity that is detached.  You have to merge the deserialized User entity into the entity manager.
$detachedIdentity = Zend_Auth::getInstance()->getIdentity();
$identity = $em->merge($detachedIdentity);

The question, is how to do this cleanly. You could look into implementing a __wakeup() magic method for your User entity, but that is also against doctrine best practices...
Source: Implementing Wakeup or Clone
Since we are talking about Zend_Auth, you could extend Zend_Auth and override the getIdentity() function so that it is entity aware.
use Doctrine\ORM\EntityManager,
    Doctrine\ORM\UnitOfWork;

class My_Auth extends \Zend_Auth
{
    protected $_entityManager;

    /**
     * override otherwise self::$_instance
     * will still create an instance of Zend_Auth
     */
    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    public function getEntityManager()
    {
        return $this->_entityManager;
    }

    public function setEntityManager(EntityManager $entityManager)
    {
        $this->_entityManager = $entityManager;
    }

    public function getIdentity()
    {
        $storage = $this->getStorage();

        if ($storage->isEmpty()) {
            return null;
        }

        $identity = $storage->read();

        $em = $this->getEntityManager();
        if(UnitOfWork::STATE_DETACHED === $em->getUnitOfWork()->getEntityState($identity))
        {
            $identity = $em->merge($identity);
        }

        return $identity;
    }
}

And than add an _init function to your Bootstrap:
public function _initAuth()
{
    $this->bootstrap('doctrine');
    $em = $this->getResource('doctrine')->getEntityManager();

    $auth = My_Auth::getInstance();
    $auth->setEntityManager($em);
}

At this point calling $user->getUserGroup()->getName(); should work as intended.

A: When you store the entity to a session (via Zend_Auth or otherwise), the object is serialized and no longer maintained by Doctrine when subsequently retrieved and unserialized.  Try merging the entity back into the EntityManager.  See http://www.doctrine-project.org/docs/orm/2.1/en/reference/working-with-objects.html


text:
Q: How to add an App.Config in Visual Studio Code? How to configure a C# program with a connection string in Visual Studio Code?
This is for .Net Core 2.2 using .Net Core SDK version 2.2.203 in Visual Studio Code 1.34.0
I have tried to add App.Config file to the project, but I'm not able to resolve this issue. Do let me know any solution to configure connection string.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Collections.Specialized;
using Dapper;

namespace Sample_Dapper
{
    class Program
    {
        static void Main(string[] args)
        {
            IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);

            var SqlString = "SELECT TOP 100 [CustomerID],[CustomerFirstName],
                             [CustomerLastName],[IsActive] FROM [Customer]";
            var ourCustomers = (List<Customer>)db.Query<Customer>(SqlString);
        }
    }
}

A: Install Microsoft.Extensions.Configuration.Json
Then add appsettings.json file to project and right click on file -properties and select copy to output as copy if newer
var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        IConfigurationRoot configuration = builder.Build();

        Console.WriteLine(configuration.GetConnectionString("Test"));

        Console.WriteLine(configuration.GetSection("SampleObj:AnyPropName").Value);

sample appsetting.json file
 {
  "SampleObj": {
    "AnyPropName" :  "testProp"
  } ,
  "ConnectionStrings": {
    "Test": "CONNECTION-STRING"
  }
}

A: Your code has ConfigurationManager.ConnectionStrings to get the connection string. This code will not work in .NET Core 2.2 and later, because ConfigurationManager.ConnectionStrings is used to get connection strings in web.config for ASP.NET project and app.config for console and Winforms/WPF projects if your app is using .NET Framework.
In .NET Core 2.0 and later, most configuration is stored as JSON file, and by default the equivalent of web.config/app.config is appsettings.json file, and you can also have your own configuration file as well, because it is highly extensible.
The official .NET Core 2.0 (or later) documentation on how to manage configuration files is available at: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2


text:
Q: Php and mysql display column names I have table with the following fields
+----+------+----------+----------+----------+
| id | name | sports_1 | sports_2 | sports_3 |
+----+------+----------+----------+----------+
|  3 | jack |        1 |        0 |        1 |
+----+------+----------+----------+----------+

I want to only display that column names that contain 1. To have the following results.
Jack does sport_1 sports_3

A: The thing you actually want is another table structure. I'll elaborate a little.
The thing you are describing is a many-to-many relationship. The sports you have in columns should actually be contained in another table called "sports" and in between the "users" table and the "sports" table you have a new table called "users_to_sports" connecting the two.
Check http://sqlrelationship.com/many-to-many-relationship/ for a more in-depth explanation

A: this is just work around and you may change the structure of your table as chrisR said
but here if you want you can look this if it help you.
    $con = mysql_connect("localhost","root","admin");
     if (!$con)
             {
              die('Could not connect ya rafik : ' . mysql_error());
              }
   mysql_select_db("mydatabase", $con);
   $query = mysql_query("SELECT * FROM mytable2 ORDER BY name ");

   // please use PDO or mysqli instead.

and then you manage results by php like this
   while ($column_data = mysql_fetch_assoc ($query)) {
          echo $column_data['name']." does : ";
        if ($column_data['sports_1'] == 1 ){echo "  Sport1  ";} else {}
        if ($column_data['sports_2'] == 1 ){echo "  Sport2  ";} else {}
        if ($column_data['sports_3'] == 1 ){echo "  Sport3  " ;} else {}
           echo "<br />" ;

      }

the database is like that
id  name    sports_1    sports_2    sports_3
1   Mark      1               0         1
2   John      0               1         1

the the result will be like that:
    John does : Sport2  Sport3
    Mark does : Sport1  Sport3


text:
Q: Geo Distance Filter with ElasticSearch always returns 0 results I am using the Geo Distance Filter with ElasticSearch and no matter what distance I search for, elasticsearch 0.90.11 returns zero results.
Here's what I did: First, delete/create a new index with the geo mapping:
curl -XDELETE 'http://localhost:9200/photos'

curl -XPOST 'http://localhost:9200/photos' -d '
{
  "mappings": {
    "pin" : {
        "properties" : {
            "location" : {
                "type" : "geo_point"
            }
        }
    }
  }
}
'

Then, add a document:
curl -XPOST 'http://localhost:9200/photos/photo?pretty=1' -d '
{
   "pin" : {
      "location" : {
         "lat" : 46.8,
         "lon" : -71.2
      }
   },
   "file" : "IMG_2115.JPG"
}
'

Then search:
curl -XGET 'http://localhost:9200/photos/_search?pretty=1&size=20' -d '
{
   "query" : {
      "match_all" : {}
   },
   "filter" : {
      "geo_distance" : {
         "distance" : "10km",
         "pin.location" : {
            "lat" : "46.8",
            "lon" : "-71.2"
         }
      }
   }
}
'

But the search yields zero hits:
{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}

Anyone know why it didn't find the document within the radius? As an interesting side note, the "filtered" syntax having both "query" and "filter" as subfields as described in the document referenced above seems to no longer work at all, seems like now "query" and "filter" need to be at the top level of the json query.
Any help appreciated ...

A: Turns out that the offical manual page is not accurate, the mapping needs to be
[Sun Feb  9 11:01:55 2014] # Request to: http://localhost:9200
curl -XPUT 'http://localhost:9200/photos?pretty=1' -d '
{
   "mappings" : {
      "photo" : {
         "properties" : {
            "Location" : {
               "type" : "geo_point"
            }
         }
      }
   }
}
'

and the records with the GPS data then need to be added like this:
[Sun Feb  9 11:01:56 2014] # Request to: http://localhost:9200
curl -XPOST 'http://localhost:9200/photos/photo?pretty=1' -d '
{
   "file" : "/home/mschilli/iphone/IMG_2115.JPG",
   "Location" : [
      46.8,
      -71.2
   ]
}
'

Then later the query
[Sun Feb  9 11:05:00 2014] # Request to: http://localhost:9200
curl -XGET 'http://localhost:9200/photos/_search?pretty=1&size=100' -d '
{
   "filter" : {
      "geo_distance" : {
         "distance" : "1km",
         "Location" : [
            36.986,
            -121.443333333333
         ]
      }
   },
   "query" : {
      "match_all" : {}
   }
}
'

will show the desired result, correctly filtering out results outside the selected GPS distance.

A: I have similar problem and spent lot of time to solve it. So maybe it can be helpful to someone.
The problem may be that if you want search by distance on nested filed property like:
something:
  properties:
    name:
      type: text
   city:
      type: nested
      properties:
         location:
           type: geo_point

You need add nested query inside main query: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html


text:
Q: Properly Populate Html Table with JSON I have this code to recieve json data from php
        $.getJSON("../controller/testController.php",{action:"one"}, function(data)
        {
            var datas = "";
        $.each(data, function(key,value)
        {
            datas += "
";
                datas += ""+value.data1+"	";
                datas += ""+value.data2+"	";
                datas += ""+value.data3+	";
            datas += "
";
        })
            $(".tables").append(datas);
        })

This is the html

1
2
3

Why i cant select the data ? im checking it with this code. Is there a better way to do this?
NOTE: With static data i can select it.
$('.tables tbody tr td').last().css("background","cyan");

UPDATE
Doing some coding i saw that if i put the "css" code inside the getJSON function, i can do the job. But doing it like this, ill cant make any manipulation of the data outside of the function (horrible coding). Any ideas to make this better?

A: Maybe you have a typo in the line :
datas += ""+value.data3	";
It should be :
datas += "" + value.data3 + "	";

A: it's typing mistake.
instead of datas += ""+value.data3	";
it should be datas += ""+value.data3+"	";
Fiddle

A: This is the code to solve the problem.
$.getJSON("../controller/testController.php",{action:"one"}, function(data)
{
    var datas = "";
$.each(data, function(key,value)
{
    datas += "
";
        datas += ""+value.data1+"	";
        datas += ""+value.data2+"	";
        datas += ""+value.data3+	";
    datas += "
";
})
    $(".tables").append(datas);
    $('.tables tbody tr td').last().css("background","cyan");
})

Putting the "css" code inside the getJSON


text:
Q: How to get the difference between the current remote state and local? I've got a repository set up and added files and pushed it ok.
Then another person cloned it on a separate pc, made some changes and pushed it also.
Now back on my pc, how can I get a difference between what's on my PC and the online repository (which is more up to date).
doing a git status - says I'm up to date with origin/master.
I don't think either of us did any branching - so we should be on the master branch.
Thanks.

A: Your local needs to actually make a call to see that the online repo has been updated.  Run git fetch.  Then you should see that your master is behind origin/master by x commits.
Git keeps a record of where it knows the remote state and uses this in git status.  It doesn't connect to the remote until you tell it to with git fetch or git pull (which is a combination of git fetch and git merge).

A: The best way to compare the changes is to check the commits one by one. Go to your remote & check the commit history. You will see that another persons commits in the history.
If you have any commits that you didn't push to master yet, it's better to create a separate branch from your current state by, git checkout -b BRANCHNAME & push it to the remote.
Then you can create a pull request from your newly created branch to master & can see the difference between two branches.

A: Run the Git Pull Command to get the difference code on to you local repository.
If you had any commits on your local repository then you need to merge the Remote code with you local repositories code.
If not then the code gets merged automatically for you.


text:
Q: Spark / PySpark: Group by any item of nested list I´m still new to Spark / PySpark and have the following question. I got a nested list with ID´s in it:
result = [[411, 44, 61], [42, 33], [1, 100], [44, 42]]

The thing I´m trying to achieve is, that if any item of sublist matches an item in another sublist the both should be merged. The result should look like this:
merged_result = [[411, 44, 61, 42, 33, 44, 42], [1,100]]

The first list in "result" matches with the fourth list. The fourth list matches with the second, so all 3 should be merged into one list. The third list doesn´t match with any other list, so it stays the same.
I could achieve this by writing loops with Python.
result_after_matching = []
for i in result:
    new_list = i
    for s in result:
        if any(x in i for x in s):
            new_list = new_list + s
    result_after_matching.append(set(new_list))

#merged_result = [[411, 44, 61, 42], [42,33,44], [1, 100], [44,42,33,411,61]]

As this is not the desired output I would need to repeat the loop and do another set() overt the "merged_result")
set([[411,44,61,42,33], [42,33,44,411,61],[1,100], [44,42,33,411,61]])
-> [[411, 44, 61, 42, 33], [1,100]]

As the list of lists, and the sublists gets bigger and bigger by time as new data will be incoming, this will not be the function to use.
Can anyone tell me if there is a function, in Spark / Pyspark, to match / merge / groupby / reduce these nested lists much easier and faster?!
Thanks a lot in advance!
MG

A: Most rdd or dataframe based solutions will probably be fairly inefficient. This is because the nature of your problem requires every element of your data set to be compared to every other element potentially multiple times. This makes it so that distributing the work across a cluster is at best inefficient.
Perhaps a different way to do this would be to reformulate this as a graph problem. If you treat each item in a list as a node on a graph, and each list as a subgraph, then the connected components of a parent graph constructed from the subgraphs will be the desired result. Here is an example using the networkx package in python:
import networkx as nx

result = [[411, 44, 61], [42, 33], [1, 100], [44, 42]]

g = nx.DiGraph()
for subgraph in result:
    g.add_path(subgraph)

u = g.to_undirected()
output=[]
for component in nx.connected_component_subgraphs(u):
    output.append(component.nodes())

print(output)
# [[33, 42, 411, 44, 61], [1, 100]]

This should be fairly efficient, but if your data is very large it will make sense to use a more scalable graph analysis tool. Spark does have a graph processing library called GraphX:
https://spark.apache.org/docs/latest/graphx-programming-guide.html
Unfortunately the pyspark implementation is lagging behind a bit. So if you intend to use something like this, you might be stuck using scala-spark or a different framework entirely for right now.

A: I think you can use aggregate action from RDD. Below I'm putting example implementation in Scala. Please note that I've used recursion, to make it more readable, but to improve performance it's good idea to reimplement those functions.
def overlap(s1: Seq[Int], s2: Seq[Int]): Boolean =
    s1.exists(e => s2.contains(e))

def mergeSeq(s1: Seq[Int], s2: Seq[Int]): Seq[Int] =
    s1.union(s2).distinct

def mergeSeqWithSeqSeq(s: Seq[Int], ss: Seq[Seq[Int]]): Seq[Seq[Int]] = ss match {
    case Nil => Seq(s)
    case h +: tail =>
        if(overlap(h, s)) mergeSeqWithSeqSeq(mergeSeq(h, s), tail)
        else h +: mergeSeqWithSeqSeq(s, tail)
}

def mergeSeqSeqWithSeqSeq(s1: Seq[Seq[Int]], s2: Seq[Seq[Int]]): Seq[Seq[Int]] = s1 match {
    case Nil => s2
    case h +: tail => mergeSeqWithSeqSeq(h, mergeSeqSeqWithSeqSeq(tail, s2))
}

val result = rdd
    .aggregate(Seq.empty[Seq[Int]]) (
       {case (ss, s) =>  mergeSeqWithSeqSeq(s, ss)},
       {case (s1, s2) => mergeSeqSeqWithSeqSeq(s1, s2)}
     )


text:
Q: Forms lead to "Page not found" in Ultimate Member plugin I use the Ultimate Member plugin to grant external members access to certain data sets, e.g. employees of their institution. There is an extra tab on the profile page of the logged-in member. All the names of the employees then appear there in a drop-down list (select). The logged-in member can select a person, click on a button and then the respective details, e.g. name, telephone number, email address, etc. will be displayed in text fields. This works fine.
I have another button that is supposed to save the respective changes which are read from the text fields. For testing purposes, it should only output the respective details using echo. However, pressing the button always leads to a "Page can't be found", although the web address does not change at all.
Here is the associated source code
function um_profile_content_miapteamtab_default( $args ) {
        $user = wp_get_current_user();
        $args = array(
        'post_type' => 'team',
        'author' => $user->ID,
        'limit' => 100,
                'posts_per_page' => -1,
        'post_status' => 'publish'
    );

    $query = new WP_Query($args);
    if ($query->have_posts()) :
                ?>

                        <form action="" method="post">

                                        <select name="teammember" id="label">
                                                <?php
                                                while ($query->have_posts()) : $query->the_post();
                                                        ?>
                                                        <option value="<?php echo get_the_ID(); ?>"><?php echo get_the_title(); ?></option>
                                                        <?php
                                                endwhile;
                                                ?>
                                        </select>

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

                        </form>

                        <?php
                        if(isset($_POST))    // checks whether any value is posted
                        {
                        $ID = $_POST['teammember'];
                                if ($ID != ''){
                                        echo '
Team Member: ' . get_the_title($ID) . '
';
                                        ?>
                                        <form action="" method="post">
                                                <input type="text" name="name" value="<?php echo get_the_title($ID); ?>">

                       >
                                                <input type="submit" value="submit">
                                        </form>
                                        <?php
                                }
                        }
                        ?>

                <?php
                        if (isset($_POST)) {
                                $name = $_POST['name'];
                                if ($name != ''){
                                        echo $name;
                                }
                        }
                ?>

                <?php
        endif;
}
add_action( 'um_profile_content_miapteamtab_default', 'um_profile_content_miapteamtab_default' );
Erweitern

Any ideads?
Best regards,
Arne


text:
Q: Allow Connection From WAN to LAN I have made a Web Server using Python Socket which I can reach with in my LAN but not reachable from the WAN. I have enabled 'Virtual Server' in my router. I think the router's Firewall is blocking it, so I tried to find any settings but I don't know where find and what to do. I am Using Router: D-link DIR-615 | Hardware version: T3 | Firmware Version: 20.22 .

*

*My Problem: Maybe I have to allow WAN connection to my LAN but I don't know how to do.

Thanks for your Help!

A: Just going off of what you said:
Your firewall is maybe not fully set up to do port forwarding to your private server. For security reasons, you will want to ensure that inbound traffic on the web ports (80/443) are forwarded to the IP of your webserver only. Youll also need your router set up with a NAT loopback policy unless you want to test your webserver on a client using a mobile phone or a hotspot. I am not sure what checking the virtual server box on your router does exactly, but, it may be something to look into and compare it to the steps i am about to provide.
Here is a link for all the steps required to open up a server to the world. Its on a different router, but the overall concepts should be the same.
https://www.sonicwall.com/support/knowledge-base/how-can-i-enable-port-forwarding-and-allow-access-to-a-server-through-the-sonicwall/170503477349850/


text:
Q: WCF Message Security with Certification without primary key I'm trying to connect to SOAP web service (JAVA) with WCF. The request must contain Timestamp and BinarySecurityToken. The problem is that a certificate I received does not contain a Private Key (and there is no way to get it) and the request fails with an error "The private key is not present in the X.509 certificate."
I tried with self-signed certificate that I created and the request message looks like it should (of course authentication fails).
<basicHttpBinding >
 <binding name="VerificacionJugadoresBinding">
  <security mode="TransportWithMessageCredential" >
    <message clientCredentialType="Certificate"/>
  </security>
 </binding>
</basicHttpBinding >

myClient.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(@"myCert.cer");

Is there any way to accomplish this without a private key? Any other options instead of WCF? It must be in .NET though.
Thanks

A: Message security with a certificate client needn't a private key of the service certificate. Only we need to do is established the trust relationship between the server and the client, namely we should install the service certificate of the server in the RootCA on the client-side, and the server is supposed to install the client certificate in the server-side RootCA.
Please refer to the below document.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/message-security-with-a-certificate-client
Feel free to let me know if the problem still exists.


text:
Q: Can't import modules is typescript I have a folder structure like this:
src\
   components\
     Home\
       index.tsx
   redux\
     reducer.ts
   index.tsx

In ./index.tsx
in have
export const App = <p> Hello World </p>

When i try to import { App } from ../index.tsx in reducer.js is say App is undefined
But if i import Home from '../components/Home' it works well.
What could be the issue?

A: import { App } from ../index? You should import js rather than jsx. Which is, I suppose, compiled and stored next to your .jsx files. You can also update your webpack config in order to import jsx directly, not sure it's an option in this case.


text:
Q: How to embed a limesurvey survey in my HTML without iframe I created a page to host some forms served by a limesurvey instance. For instance I used an iframe to embed them. But it created some problems. The worst is that in the second question group, which is smaller, the parent focus should go to the page top, otherwise the page appears clear because the form content was rendered on the top, and the iframe size was not resized.
Maybe it is just a limitation of mine dealing with iframe. But it would be nice if limesurvey offer other ways to embed surveys.
Any help is welcome.

A: I still don't know how to do it without Iframes on 2+ version.
The problem of multiple pages surveys standing on the bottom of the page can be handled with a small javascript workaround:
Edit the survey and add the following code at 'edit text elements' (toggle to 'source' mode at wysiwyg editor):


text:
Q: Spring Security: Set GrantedAuthorities Is there anyway to set the List<GrantedAuthority> in the Authentication/UserDetailsImpl object? In my application, I have two layers of security, one for logging in (which uses my custom login authenticator, in the class I set the Authentication object using the UsernamePasswordAuthenticationToken) and one for a "challenge question" where the user is prompted to answer a particular question.
What I want to do is add a GrantedAuthority to the current List<GrantedAuthority>, which was created during the login process, after the user answers the challenge question.
Is this possible?

A: you can do it with following code:
Collection<SimpleGrantedAuthority> oldAuthorities = (Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext().getAuthentication().getAuthorities();
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ANOTHER");
List<SimpleGrantedAuthority> updatedAuthorities = new ArrayList<SimpleGrantedAuthority>();
updatedAuthorities.add(authority);
updatedAuthorities.addAll(oldAuthorities);

SecurityContextHolder.getContext().setAuthentication(
        new UsernamePasswordAuthenticationToken(
                SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
                SecurityContextHolder.getContext().getAuthentication().getCredentials(),
                updatedAuthorities)
);

A: The UserDetails.getAuthorities() method just returns a Collection<GrantedAuthority> object. You can use the appropriate Collection method to add your new authority to that collection.
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
    ((UserDetails) principal).getAuthorities().add(New GrantedAuthorityImpl("ROLE_FOO"));
}

Selah.


text:
Q: The name <> does not exist in the namespace <> (for Library project) I'm new to C#/Windows store apps development and I have a problem:
I'm getting
The name "CustomTemplate1" does not exist in the namespace "using:QSTLibrary.WIN8"
I work on a project which has 2 libraries (one portable(without any GUI) and one platform specific(Win store apps)) and a startup project which is based on these 2 libs.
On the platform-specific library I want to add a templated control, but when adding it using the add -> new item -> templated control the Generic.xaml from the auto-generated "Themes" folder has the above error.
Here is Generic.xaml:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:QSTLibrary.WIN8">

    <Style TargetType="local:CustomTemplate1"> //HERE IS THE PROBLEM !!!!
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:CustomTemplate1">
                    <Border
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Here is CustomTemplate1:
using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;

// The Templated Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234235

namespace QSTLibrary.WIN8
{
    public sealed class CustomTemplate1 : Control
    {
        public CustomTemplate1()
        {
            this.DefaultStyleKey = typeof(CustomTemplate1);
        }
    }
}

QSTLibrary.WIN8 is the platform-specific library

Please help me with this issue.

A: I've solve it by copying the content of the Generic.xaml, delete the Generic.xaml, build, add again a new xaml file under Themes folder (name it Generic.xaml) and paste the initial content of the Generic.xaml. build again and works. My conclusion is that I must first compile the lib containing the CustomTemplate1.cs and after this compile, the lib will be able to add references to the CustomTemplate1.cs. Because of the initial error, the lib didn't compiled, so removing the file with the error, compiling, adding again the xaml was my way to solve this issue. Looks like a Visual Studio bug for me.


text:
Q: How to proceed from here in this infinite summation
Evaluate $$\sum_{n=1}^{\infty}\frac{(-1)^n n^2}{1+n^4}$$
I rewrote this as $$\sum_{n=1}^{\infty} \left(- \frac{\left(-1\right)^{n} \sqrt{2} n}{4 \left(n^{2} + \sqrt{2} n + 1\right)} + \frac{\left(-1\right)^{n} \sqrt{2} n}{4 \left(n^{2} - \sqrt{2} n + 1\right)}\right)$$ But this is not a telescopic series. How should I proceed now$?$

Also, does I need thorough knowledge of complex analysis to solve these kind of problems$?$ Any idea is greatly appreciated.

A: Why not to play with the roots of unity writing
$$\frac {n^2}{n^4+1}=\frac {n^2}{(n-a)(n-b)(n-c)(n-d)}$$ where
$$a=-\frac{1+i}{\sqrt{2}}\qquad b=\frac{1+i}{\sqrt{2}}\qquad c=-\frac{1-i}{\sqrt{2}}\qquad d=\frac{1-i}{\sqrt{2}}$$ Using partial fraction decomposition
$$\frac{a^2}{(a-b) (a-c) (a-d) (n-a)}+\frac{b^2}{(b-a) (b-c)
   (b-d) (n-b)}+$$ $$\frac{c^2}{(c-a) (c-b) (c-d)
   (n-c)}+\frac{d^2}{(d-a) (d-b) (d-c) (n-d)}$$ to face four sums looking like
$$\sum_{n=1}^\infty \frac {(-1)^n}{n-k}=\frac{1}{2} \left(\psi
  \left(\frac{1-k}{2}\right)-\psi\left(\frac{2-k}{2}\right)\right)$$
This leads to a beautiful result.


text:
Q: Searching each property value of an IQueryable collection of T against the value of a search query. How do I test for NOT NULL and CONTAINS together? I am trying search each property value of an IQueryable collection of T against the value of a search query.  I have the following function and would like to know how do I ALSO test for NOT NULL and CONTAINS together?
private Expression<Func<T, bool>> PropertySearch
{
  get
  {
     // Object that is passed to the lambda expression
     ParameterExpression instance = Expression.Parameter(typeof(T), "val");
     Expression whereExpr = Expression.Constant(true); // default is val => True

     var _properties = typeof(T).GetProperties();
     foreach (var prop in _properties)
     {
        var query = _httpRequest["query"].ToLower();
        var property = Expression.Property(instance, prop);
        var toStringCall = Expression.Call(Expression.Call(
            property,
            "ToString",
            new Type[0]),
            typeof(string).GetMethod("ToLower", new Type[0]));
        whereExpr = Expression.And(whereExpr,
            Expression.Call(toStringCall, typeof(string).GetMethod("Contains"),
            Expression.Constant(query)));
     }
     return Expression.Lambda<Func<T, bool>>(whereExpr, instance);
}}

A: I have created a search extensions nuget package that performs this type of check.  For your example I would do something like the following.
Note, this is without an IDE so may have some errors
/* *** Start: These can be made private reaonly fields ***/
var comparisonExpr = Expression.Constant(StringComparison.OrdinalIgnoreCase);
var zeroExpression = Expression.Constant(0)
var nullExpression = Expression.Constant(null)
MethodInfo IndexOfMethod = typeof(string).GetMethod("IndexOf", new[] { typeof(string), typeof(StringComparison) });
/* *** End ***/

Expression finalExpression = null
ParameterExpression instance = Expression.Parameter(typeof(T), "val");
var _properties = typeof(T).GetProperties();
var query = _httpRequest["query"].ToLower();
var queryExpr = Expression.Constant(query);

foreach (var prop in _properties)
{
    //Get property
    var propertyExpr = Expression.Property(instance, prop);
    //Get property as string
    var propStringExpr = Expression.Call(property, "ToString", new Type[0]);
    //Perform IndexOf call
    var indexOfExpr = Expression.Call(propStringExpr,
                                       IndexOfMethod,
                                       queryExpr,
                                       comparisonExpr);

    // Check index of is greater than or equal to zero
    var containsExpr = Expression.GreaterThanOrEqual(containsExpr, zeroExpression);

    if(finalExpression == null)
    {
        finalExpression = containsExp;
    }
    else
    {
        finalExpression = Expression.AndAlso(containsExpr);
    }
}

return Expression.Lambda<Func<T, bool>>(finalExpression, instance);

I've removed the need for ToLower() and instead used IndexOf with a string comparison type
If you want to see how I have achieved similar functionality, take a look at NinjaNye.SearchExtensions on Github
https://github.com/ninjanye/SearchExtensions
If you wanted to search a collection of IQueryable you could use NinjaNye.SearchExtensions as follows
string query = _httpRequest["query"];
var result = data.SearchAll().Containing(query);

This will search all string properties (not all properties as you have above) and return just those where any property mathes the search term.
Hope this helps

A: You could probably use PredicateBuilder so you don't have to mess with expression trees yourself.