Q: Is it possible always to force a new thread with Task? I am trying to create a new thread each time Task.Factory.StartNew is called. The question is how to run the code bellow without throwing the exception:
static void Main(string[] args)
{
    int firstThreadId = 0;

    Task.Factory.StartNew(() => firstThreadId = Thread.CurrentThread.ManagedThreadId);

    for (int i = 0; i < 100; i++)
    {
        Task.Factory.StartNew(() =>
        {
            while (true)
            {
                Thread.Sleep(1000);
                if (firstThreadId == Thread.CurrentThread.ManagedThreadId)
                    throw new Exception("The first thread is reused.");
            }
        });
    }
    Console.Read();
}

EDIT: the new code if you comment the first for statement there is no problem. But if you have it, WOW, the message "Thread reused" is written to the console. Can you explain that because I am really confused.
static void Main(string[] args)
{
    ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();

    for (int i = 0; i < 10; i++)
    {
        Task.Factory.StartNew(() =>
        {
            Task.Factory.StartNew(() =>
            {
                startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId,
                    Thread.CurrentThread.ManagedThreadId, (a, b) => b);
            }, TaskCreationOptions.LongRunning);

            for (int j = 0; j < 100; j++)
            {
                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(10);
                        if (startedThreads.ContainsKey(
                            Thread.CurrentThread.ManagedThreadId))
                                Console.WriteLine("Thread reused");
                    }
                }, TaskCreationOptions.LongRunning);
            }
        });
    }

    Console.Read();
}

A: Adding to Jon Skeet's answer, if you want to guarantee that a new thread is created every time, you can write your own TaskScheduler that creates a new thread.

A: Try this:
var taskCompletionSource = new TaskCompletionSource<bool>();
Thread t = new Thread(() =>
{
    try
    {
        Operation();
        taskCompletionSource.TrySetResult(true);
    }
    catch (Exception e)
    {
        taskCompletionSource.TrySetException(e);
    }
});
void Operation()
{
    // Some work in thread
}
t.Start();
await taskCompletionSource.Task;

You also can write extension methods for Action, Func and so on.
For example:
public static Task RunInThread(
    this Action action,
    Action<Thread> initThreadAction = null)
{
    TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();

    Thread thread = new Thread(() =>
    {
        try
        {
            action();
            taskCompletionSource.TrySetResult(true);
        }
        catch (Exception e)
        {
            taskCompletionSource.TrySetException(e);
        }
    });
    initThreadAction?.Invoke(thread);
    thread.Start();

    return taskCompletionSource.Task;
}

or
public static Task<TResult> RunInThread<T1, T2, TResult>(
    this Func<T1, T2, TResult> function,
    T1 param1,
    T2 param2,
    Action<Thread> initThreadAction = null)
{
    TaskCompletionSource<TResult> taskCompletionSource = new TaskCompletionSource<TResult>();

    Thread thread = new Thread(() =>
    {
        try
        {
            TResult result = function(param1, param2);
            taskCompletionSource.TrySetResult(result);
        }
        catch (Exception e)
        {
            taskCompletionSource.TrySetException(e);
        }
    });
    initThreadAction?.Invoke(thread);
    thread.Start();

    return taskCompletionSource.Task;
}

and use it like that:
var result = await some_function.RunInThread(param1, param2).ConfigureAwait(true);

A: Hello and thank you all for the answers. You all got +1. All suggested solution did not work for my case. The problem is that when you sleep a thread it will be reused at some point of time. The people above suggested:

*

*using LongRunning => This will not work if you have nested/child
tasks

*custom task scheduler => I tried to write my own and also tried this
ThreadPerTaskScheduler which also di not work.

*using pure threads => Still failing...

*you could also check this project at Multithreading.Scheduler github
My solution
I don't like it but it works. Basically I block the thread so it cannot be reused. Bellow are the extension methods and a working example. Again, thank you.
https://gist.github.com/4150635
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public static class ThreadExtensions
    {
        /// <summary>
        /// Blocks the current thread for a period of time so that the thread cannot be reused by the threadpool.
        /// </summary>
        public static void Block(this Thread thread, int millisecondsTimeout)
        {
            new WakeSleepClass(millisecondsTimeout).SleepThread();
        }

        /// <summary>
        /// Blocks the current thread so that the thread cannot be reused by the threadpool.
        /// </summary>
        public static void Block(this Thread thread)
        {
            new WakeSleepClass().SleepThread();
        }

        /// <summary>
        /// Blocks the current thread for a period of time so that the thread cannot be reused by the threadpool.
        /// </summary>
        public static void Block(this Thread thread, TimeSpan timeout)
        {
            new WakeSleepClass(timeout).SleepThread();
        }

        class WakeSleepClass
        {
            bool locked = true;
            readonly TimerDisposer timerDisposer = new TimerDisposer();

            public WakeSleepClass(int sleepTime)
            {
                var timer = new Timer(WakeThread, timerDisposer, sleepTime, sleepTime);
                timerDisposer.InternalTimer = timer;
            }

            public WakeSleepClass(TimeSpan sleepTime)
            {
                var timer = new Timer(WakeThread, timerDisposer, sleepTime, sleepTime);
                timerDisposer.InternalTimer = timer;
            }

            public WakeSleepClass()
            {
                var timer = new Timer(WakeThread, timerDisposer, Timeout.Infinite, Timeout.Infinite);
                timerDisposer.InternalTimer = timer;
            }

            public void SleepThread()
            {
                while (locked)
                    lock (timerDisposer) Monitor.Wait(timerDisposer);
                locked = true;
            }

            public void WakeThread(object key)
            {
                locked = false;
                lock (key) Monitor.Pulse(key);
                ((TimerDisposer)key).InternalTimer.Dispose();
            }

            class TimerDisposer
            {
                public Timer InternalTimer { get; set; }
            }
        }
    }

    class Program
    {
        private static readonly Queue<CancellationTokenSource> tokenSourceQueue = new Queue<CancellationTokenSource>();
        static void Main(string[] args)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            tokenSourceQueue.Enqueue(tokenSource);

            ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(1000);
                Task.Factory.StartNew(() =>
                {
                    startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b);
                    for (int j = 0; j < 50; j++)
                        Task.Factory.StartNew(() => startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b));

                    for (int j = 0; j < 50; j++)
                    {
                        Task.Factory.StartNew(() =>
                        {
                            while (!tokenSource.Token.IsCancellationRequested)
                            {
                                if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) Console.WriteLine("Thread reused");
                                Thread.CurrentThread.Block(10);
                                if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId)) Console.WriteLine("Thread reused");
                            }
                        }, tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
                        .ContinueWith(task =>
                        {
                            WriteExceptions(task.Exception);
                            Console.WriteLine("-----------------------------");
                        }, TaskContinuationOptions.OnlyOnFaulted);
                    }
                    Thread.CurrentThread.Block();
                }, tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default)
                .ContinueWith(task =>
                {
                    WriteExceptions(task.Exception);
                    Console.WriteLine("-----------------------------");
                }, TaskContinuationOptions.OnlyOnFaulted);
            }

            Console.Read();
        }

        private static void WriteExceptions(Exception ex)
        {
            Console.WriteLine(ex.Message);
            if (ex.InnerException != null)
                WriteExceptions(ex.InnerException);
        }
    }
}

A: If you specify TaskCreationOptions.LongRunning when starting the task, that provides a hint to the scheduler, which the default scheduler takes as an indicator to create a new thread for the task.
It's only a hint - I'm not sure I'd rely on it... but I haven't seen any counterexamples using the default scheduler.

A: Just start threads with new Thread() and then Start() them
static void Main(string[] args)
{
    ConcurrentDictionary<int, int> startedThreads = new ConcurrentDictionary<int, int>();

    for (int i = 0; i < 10; i++)
    {
        new Thread(() =>
        {
            new Thread(() =>
            {
                startedThreads.AddOrUpdate(Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId, (a, b) => b);
            }).Start();

            for (int j = 0; j < 100; j++)
            {
                new Thread(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(10);
                        if (startedThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId))
                            Console.WriteLine("Thread reused");
                    }
                }).Start();
            }
        }).Start();
    }

    Console.Read();

}

Tasks are supposed to be managed by the scheduler. The whole idea of Tasks is that the runtime will decide when a new thread is needed. On the other hand if you do need different threads chances are something else in the code is wrong like overdependency on Thread.Sleep() or thread local storage.
As pointed out you can create your own TaskScheduler and use tasks to create threads but then why use Tasks to begin with?

A: Here is a custom TaskScheduler that executes the tasks on a dedicated thread per task:
public class ThreadPerTask_TaskScheduler : TaskScheduler
{
    protected override void QueueTask(Task task)
    {
        var thread = new Thread(() => TryExecuteTask(task));
        thread.IsBackground = true;
        thread.Start();
    }

    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
    {
        return TryExecuteTask(task);
    }

    protected override IEnumerable<Task> GetScheduledTasks() { yield break; }
}

Usage example:
var parallelOptions = new ParallelOptions()
{
    MaxDegreeOfParallelism = 3,
    TaskScheduler = new ThreadPerTask_TaskScheduler()
};

Parallel.ForEach(Enumerable.Range(1, 10), parallelOptions, item =>
{
    Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}" +
        $" [{Thread.CurrentThread.ManagedThreadId}]" +
        $" Processing #{item}" +
        (Thread.CurrentThread.IsBackground ? ", Background" : "") +
        (Thread.CurrentThread.IsThreadPoolThread ? ", ThreadPool" : ""));
    Thread.Sleep(1000); // Simulate CPU-bound work
});

Output:
20:38:56.770 [4] Processing #3, Background
20:38:56.770 [5] Processing #2, Background
20:38:56.770 [1] Processing #1
20:38:57.782 [1] Processing #4
20:38:57.783 [8] Processing #5, Background
20:38:57.783 [7] Processing #6, Background
20:38:58.783 [1] Processing #7
20:38:58.783 [10] Processing #8, Background
20:38:58.787 [9] Processing #9, Background
20:38:59.783 [1] Processing #10

Try it on Fiddle.
This custom TaskScheduler allows the current thread to participate in the computations too. This is demonstrated in the above example by the thread [1] processing the items #1, #4, #7 and #10. If you don't want this to happen, just replace the code inside the TryExecuteTaskInline with return false;.
Another example, featuring the Task.Factory.StartNew method. Starting 100 tasks on 100 different threads:
var oneThreadPerTask = new ThreadPerTask_TaskScheduler();
Task[] tasks = Enumerable.Range(1, 100).Select(_ =>
{
    return Task.Factory.StartNew(() =>
    {
        Thread.Sleep(1000); // Simulate long-running work
    }, default, TaskCreationOptions.None, oneThreadPerTask);
}).ToArray();

In this case the current thread is not participating in the work, because all tasks are started behind the scenes by invoking their Start method, and not the
RunSynchronously.


Q: How to order by time and time only in C#? I have this recorded in SQL Server:
1- startTime (datetime):  5/2/2009  08:30   (brazilian time format: d/m/y)
2- startTime (datetime):  4/2/2009  14:30   (brazilian time format: d/m/y)
My application just records time... the date it's SQL that generates by itself be getting the date of today.
When I ask VS 2008 to order this datetime fields, it returns me that code #2 is before #1, because 4/2/2009 comes before 5/2/2009.
But, actually I want it to order by time only and ignore the date.
Is it possible??
Thanks!!
André

A: You might also try fixing your app so it always saves the same base date with the time (like '01/01/1900' or whatever) and then you do not have to do all these slow and inefficient date stripping operations every time you need to do a query.
Or as Joel said, truncate or strip off the date portion before you do the insert or update.

A: from d in dates
     orderby d.TimeOfDay
     select d;

or
dates.OrderBy(d => d.TimeOfDay);

Note: This will work as long as this is plain LINQ and not LINQ-to-SQL. If you're using LINQ-to-SQL to query your database, you'll need something that will translate to SQL.

A: Well, you can't really store a datetime without a date, but you could just store the total seconds as an double (using @florian's method).
You'd have to add a second method to convert this back to a date in your object, if you still need a date, such as:
public class BusinessObjectWithDate
{
    private string _someOtherDbField = "";
    private double _timeInMS = 0; // save this to the database

    // sort by this? in sql or in code.  You don't really need this
    // property, since TimeWithDate actually saves the _timeInMS field
    public double TimeInMS {
        get { return _timeInMS; }
    }
    public DateTime TimeWithDate { // sort by this too, if you want
        get { return (new DateTime(1900,1,1).AddMilliseconds(_timeInMS)); }
        set { _timeInMS = value.TimeOfDay.TotalMilliseconds; }
    }
}

var f = new BusinessObjectWithDate();
MessageBox.Show( f.TimeWithDate.ToString() );  // 1/1/1900 12:00:00 AM
f.TimeWithDate = DateTime.Now;
MessageBox.Show( f.TimeWithDate.ToString() );  // 1/1/1900 1:14:57 PM

You could also just store the real date time, but always overwrite with 1/1/1900 when the value gets set.  This would also work in sql
public class BusinessObjectWithDate
{
    private DateTime _msStoredInDate;
    public DateTime TimeWithDate
    {
        get { return _msStoredInDate; }
        set {
            var ms = value.TimeOfDay.TotalMilliseconds;
            _msStoredInDate = (new DateTime(1900, 1, 1).AddMilliseconds(ms));
        }
    }
}

A: Try this in your sql:
ORDER BY startTime - CAST(FLOOR(CAST(startTime AS Float)) AS DateTime)


Q: Get Values From a Specific Column Into a Dropdown Want to ask if there's a quick way, an automated or using formulas for this scenario.
So I have "config" sheet, and each columns is a list used for a specific dropdown.
config!A:A = clientA
config!B:B = clientB
In a "summary" sheet, I need to add a dropdown in column C depending on the column A
For example summary!A2 contains "client A" so the dropdown in summary!C2 will show the list of clientA
And summary!A3 contains "client B" so the dropdown in summary!C3 will show the list of clientB
What I currently do is named the range each in the "config" then in "summary" I put the Data Validation for the specific name.
I was wondering if there's a custom formula that I can put in the Data Validation for Column C that depends on the value in column A. The only challenge is there are spaces so in the Named Range I remove the space. And since it depends on the column, the row number is moving.
Looking for a formula since I am avoiding App Script for this specific file. Thanks
Hopefully someone could help me on this.
Thanks much.
You are all awesome!

A: What you can do is set an Auxiliary sheet (or extra columns far in "Summary"). You can set Summary!C2 the next Data Validation:

=Auxiliary!A1:1

Open the settings of that data validation and make sure there are no anchors (no $, for example A$1). If there is some, delete them
Close it and then copy and paste special - Data Validation only to the rest of the cells

This way C2 will be associated with row 2 from Auxiliary, C3 with row 3 and so on
Then, you can go to Auxiliary and set a formula in each row to filter the values according to B2, B3 (or however you identify the client... (a Query, or Filter) --> You'll probably need to transpose the information, so the list becomes a row
With that done, each data validation will depend now on the value of that row

Re-reading your example, you can do the same but instead of filter you can transpose the entire Config sheet and you'll have a row per client
......
You have an example here: https://docs.google.com/spreadsheets/d/1jF5XoBkQll5tHEjADg508NMznmbuB43tyWv5R2S1mM8/edit?usp=sharing


Q: Entity Framework object graph deletion with Breeze I am encountering a recurring problem that just makes no sense, and hoping someone (in the Breeze team?) can shed some light.
The following model illustrates the entities in question.

As you can see, I'm adhering pretty strictly to Entity Framework conventions in my property names, and as a result, if I check in SQL the cascade on delete rules are set by EF code first when it creates the db.
Now, when I try to delete a BusUnit manually in SQL, the delete cascades correctly and the corresponding BusUnitDimensions are also deleted, as it should be. Likewise, if I delete a Dimension in SQL, the corresponding BusUnitDimensions are also deleted.
However, in my application, if I mark a BusUnit as setDeleted with Breeze and then try saveChanges, I get the following error.
The operation failed: The relationship could not be changed because one
or more of the foreign-key properties is non-nullable. When a change is
made to a relationship, the related foreign-key property is set to a null
value. If the foreign-key does not support null values, a new relationship
must be defined, the foreign-key property must be assigned another
non-null value, or the unrelated object must be deleted.

Strangely though, if I mark a Dimension for deletion and then save (within Breeze), the cascaded delete works correctly and both the Dimension and its corresponding BusUnitDimensions are deleted.
So, why the inconsistency? Why are the cascaded delete rules in SQL not being applied for BusUnits but yet they're working for Dimensions? I've read elsewhere that Breeze does not support cascaded deletes, but then why is my Dimensions case working?

EDIT:
I've removed my previous edits as they weren't relevant. The changes below follow on from Ward's answer...
My model now looks like this, and BusUnitDims now uses BusUnitId and DimId as a compound key, and I've added a bool, IsBud for the purposes of payload.

I haven't yet implemented deletes for BusUnits, but already if I try delete a Dim, I'm getting the same error message:
The operation failed: The relationship could not be changed because one
or more of the foreign-key properties is non-nullable. When a change is
made to a relationship, the related foreign-key property is set to a null
value. If the foreign-key does not support null values, a new relationship
must be defined, the foreign-key property must be assigned another
non-null value, or the unrelated object must be deleted.

I have noticed that cascaded deletes is no longer enabled, and in fact, to get EF to build the database I to add the following configuration:
modelBuilder.Entity<BusUnitDim>()
    .HasRequired(bud => bud.BusUnit)
        .WithMany(bu => bu.BusUnitDims)
        .HasForeignKey(bud => bud.BusUnitId)
        .WillCascadeOnDelete(false);

modelBuilder.Entity<BusUnitDim>()
    .HasRequired(bud => bud.Dim)
        .WithMany(d => d.BusUnitDims)
        .HasForeignKey(bud => bud.DimId)
        .WillCascadeOnDelete(false);

So, with cascading now explicitly not in place, I can understand why the error occurs. Does that imply that in the controller, one has to specifically mark each map for deletion when deleting a parent Dim or BusUnit and before saveChanges is called, or is there some way to configure EF to take advantage of cascaded deletes as this would hugely simplify the code in my controller?
(PS: it gets even more complex, because BusUnitDims ends up having a further join table of its own, MetricBusUnitDims to accommodate yet another entity in the model and their relationships. This is why I'm trying to get the principles right early on)

EDIT: (A CONTROLLER SOLUTION FOR BUSUNITS)
So, the following approach works for BusUnits:
function deleteBusUnit(busUnitVm) { // note that you pass in the item viewmodel, not the entity
    var busUnit = busUnitVm.busUnit;
    var mapVms = busUnitVm.dimMapVms;
    var dimHash = createBusUnitDimHash(busUnit);

    mapVms.forEach(function (mapVm) {
        var map = dimHash[mapVm.dim.id];
        if (map) {
            datacontext.markDeleted(map);
        }
    });
    datacontext.markDeleted(busUnit);
    save().then(function() { getDBoardConfig(); });
    }
}

Is this the correct approach? if so, I'll still have to figure out the following:

*

*How to approach Dims. These are different becuase the item viewmodel is defined for BusUnits.

*How to approach the situation where there is a join tabel one level down, e.g. MetricBusUnitDIm.

EDIT: (A CONTROLLER SOLUTION FOR DIMS)
function deleteDim(dim) {
    return bsDialog.deleteDialog(dim.name, true)
        .then(function () {
            vm.busUnitVms.forEach(function (busUnitVm) {
                busUnitVm.busUnit.busUnitDims.forEach(function (bud) {
                    if (bud.dimId === dim.id) {
                        datacontext.markDeleted(bud);
                    }
                });
            });
            datacontext.markDeleted(dim);
            save().then(function () { getDboardConfig(); });
        });
}

A: I believe your problems are traceable to the fact that your mapping table BusUnitDimension has its own primary key, Id, as opposed to the more typical approach in which the BusUnitId and DimensionId FK properties together comprise the compound primary key of BusUnitDimension.

Observe that OrderDetails in Northwind and the HeroPoweMap in the Breeze many-to-many example have compound keys.

Your choice creates complications.
First, it becomes possible to create multiple BusUnitDimension entities representing the same association between BusUnit and Dimension (i.e., they all have the same pair of FKs). The database may be able to prevent this (it's been a long time since I looked) but whether it does or doesn't, it won't prevent you from creating those duplicates in Breeze ... and maybe not in EF either.
Secondly, it opens you up to the problem you're currently facing. If those mapping entities are in the DbContext when you perform the delete, EF may (apparently does) try to null their FK properties as it sets either BusUnit or Dimension to the deleted state.
You can get around this, as has been suggested, by making both the BusUnitId and DimensionId FK properties nullable. But that is contrary to the semantics as a BusUnitDimension must link a real BusUnit to a real Dimension; they aren't optional. The practical consequence may be that you don't get cascade delete from the EF perspective if you do this (not sure if the DB will enforce that either). That means you'd have orphaned BusUnitDimension rows in your database with one or both FKs being null. I speculate because I'm not used to getting into this kind of trouble.
Another approach would be to set their FK values to zero (I think Breeze does this for you). Of course this implies the existence of BusUnit and Dimension table rows with Id == 0, if only during the delete operation.

Btw, you could actually have such  "sentinel entities" in your DB.

You must make sure that these BusUnitDimension are in the deleted state or EF (and the DB) will either reject them (referential integrity constraint) or orphan them (you'll have BusUnitDimension rows in your database with one or both FKs being zero).
Alternatively, if you know that the DB will cascade delete them, you can simply remove them from the DbContext (remove from the EntityInfoMap in the EFContextProvider). But now you have to tell the Breeze client to get rid of them too if it happens to have them hanging around.
Enough Already!
These wandering thoughts should tell you that you've got yourself in a jam here with way too much bookkeeping ... and all because you gave BusUnitDimension its own Id primary key.
It gets a lot easier if you give BusUnitDimension the compound key, {BusUnitId, DimensionId}. You must also give it a payload property (anything will do) to prevent EF from hiding it in its "many-to-many" implementation because Breeze doesn't handle that. Adding any nonsense property will do the trick.
HTH

A: That has nothing to do with Breeze.. The originating message is from Entity Framework..
inside BusUnitDimension Model update BusUnitId property to:
 public Nullable<int> BusUnitId { get; set; }

Notice the Nullable struct..


Q: Rename iTunes files with AppleScript I've got this beautiful AppleScript inside iTunes which relocates selected files to my holy music folder. However I'd also like to rename the file to {Artist} - {Trackname}.extension (extension is mp3 99% of the time).
While artist and trackname are known earlier in the script I've got no clue how to also make them available in the move_the_files-function.
I hope any AppleScript (self-flagellating) enthusiasts can help me.
This is the script:
property my_title : "Re-Locate Selected"
global selectedTracks, originalLocs
global newDirectory

tell application "iTunes"
    ok_v(get version) of me

    set selectedTracks to selection
    if selectedTracks is {} then return
    if (get class of (item 1 of selectedTracks)) is not file track then return

    set originalLocs to {}
    repeat with i from 1 to (length of selectedTracks)
        tell item i of selectedTracks to set {nom, loc, artist} to {get name, get location, get artist}
        # log ("artis" & artist)
        if loc is missing value then
            display dialog "The file for \"" & nom & "\" appears to be missing. ..." buttons {"Cancel", "OK, Skip It"} default button 1 with icon 2 giving up after 30 with title "Need a decision..."
        end if
        set end of originalLocs to (loc as text)
    end repeat

    # OKAY to proceed

    display dialog "This script will re-locate the files of the selected tracks to a new folder. All meta-data will be preserved." buttons {"Cancel", "Execute"} default button 2 with title my_title
    # set newDirectory to (choose folder with prompt "Move files of selected tracks to:")
    set newDirectory to "/Volumes/Daten/Musik/Tracks/2014/12"

    #   log ("rez: " & newDirectory)

    my move_the_files()

    tell application "iTunes" to if (get frontmost) then display dialog "Done, handsome <3!" buttons {"Cool"} default button 1 with title my_title giving up after 15

end tell

to move_the_files()
    repeat with t from 1 to (length of selectedTracks)
        try
            with timeout of 300 seconds
                set f to (item t of originalLocs) as text
                do shell script "cp -p " & quofo(f) & space & quofo(newDirectory)
                relocate((item t of selectedTracks), fig_new_loc(f))
                tell application "Finder" to delete f
            end timeout
        on error m
            logger(m)
        end try
    end repeat
end move_the_files

to fig_new_loc(f)
    return (newDirectory & (last item of text_to_list(f, ":"))) as text
end fig_new_loc

on quofo(t)
    return (quoted form of POSIX path of (t as text))
end quofo

on ok_v(v)
    if (do shell script ("echo " & quoted form of (v as text) & "|cut -d . -f 1")) as integer < 10 then
        display dialog return & "This script requires iTunes v10.0 or better..." buttons {"Cancel"} default button 1 with icon 0 giving up after 15 --with title my_title
    end if
end ok_v

to relocate(t, nf)
    tell application "iTunes" to set location of t to (nf as alias)
end relocate

on replace_chars(txt, srch, repl)
    set text item delimiters to srch
    set item_list to every text item of txt
    set text item delimiters to repl
    set txt to item_list as string
    set text item delimiters to ""
    return txt
end replace_chars

on text_to_list(txt, delim)
    set saveD to text item delimiters
    try
        set text item delimiters to {delim}
        set theList to every text item of txt
    on error errStr number errNum
        set text item delimiters to saveD
        error errStr number errNum
    end try
    set text item delimiters to saveD
    return (theList)
end text_to_list

on list_to_text(theList, delim)
    set saveD to text item delimiters
    try
        set text item delimiters to {delim}
        set txt to theList as text
    on error errStr number errNum
        set text item delimiters to saveD
        error errStr number errNum
    end try
    set text item delimiters to saveD
    return (txt)
end list_to_text

to logger(t)
    log t
    try
        do shell script "logger -t" & space & quoted form of my_title & space & quoted form of (t as text)
    end try
end logger

A: Using cp unix command, you can copy and rename at same time.
I changed a bit your script to reduce it and I set the copy/rename inside the main loop. remove the "--" before the "set location" and the do shell script "rm". I leave them to be more safe for debugging.
On first row, I assigned, for my tests, the Newdirectory to my desktop. you must adjust this.
set NewDirectory to (path to desktop folder from user domain) as string -- my desktop for example

tell application "iTunes"
    ok_v(get version) of me

    set selectedTracks to selection
    if selectedTracks is {} then return
    if (get class of (item 1 of selectedTracks)) is not file track then return

    set originalLocs to {}
    repeat with i from 1 to (count of selectedTracks)
        tell item i of selectedTracks to set {TName, Tloc, Tartist} to {get name, get location, get artist}
        if Tloc is missing value then
            display dialog "The file for \"" & TName & "\" appears to be missing. ..." buttons {"Cancel", "OK, Skip It"} default button 1 with icon 2 giving up after 30 with title "Need a decision..."
        end if
        tell application "Finder" to set FExt to name extension of Tloc
        set NewName to NewDirectory & Tartist & "_" & TName & "." & FExt
        do shell script "cp " & quoted form of (POSIX path of Tloc) & " " & quoted form of (POSIX path of NewName)
        --set location of (item i of selectedTracks) to NewName
        --do shell script "rm " & quoted form of (posix path of Tloc)
    end repeat
end tell

on ok_v(v)
if (do shell script ("echo " & quoted form of (v as text) & "|cut -d . -f 1")) as integer < 10 then
    display dialog return & "This script requires iTunes v10.0 or better..." buttons {"Cancel"} default button 1 with icon 0 giving up after 15 --with title my_title
end if
end ok_v


Q: React Router not working correctly I am new to react and have no idea why this wouldnt be working.
My router code is here:
import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './components/App';
import HomePage from './components/home/HomePage';

export default (
  <Route path="/" component={App}>
    <IndexRoute component={HomePage} />
    <Route path="example" component={HomePage} />
  </Route>
);

So what happens with this code is:
localhost/ displays fine
localhost/example does not display
localhost/example link from the header on the homepage displays, but pressing refresh does not
Thanks for any help, I appreciate it!
here is my webpack config:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  context: path.join(__dirname, "/client"),
  entry: [
    'webpack-dev-server/client?http://127.0.0.0:5000/',
    'webpack/hot/only-dev-server',
    'react-hot-loader/patch',
    './src/index.js'
  ],
  output: {
    path: path.join(__dirname, "/client/dist"),
    filename: '[name].js',
    publicPath: '/'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  devServer: {
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [ 'babel-loader', 'react-hot-loader/webpack' ],
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './static/template.html',
      inject: 'body',
      filename: 'index.html'
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ]
};

app.js snippet:
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(__dirname + 'client/dist'));
app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    hot: true,
    historyApiFallback: true,
    stats: {
        colors: true
    }
}));

I am using localhost:5000 . The question linked did not fix my problem

A: FYI, Starting in version 4.0, React Router no longer uses the IndexRoute.
Also for your path, change "example" to "/example"


Q: Swift 3 xcode 8 failed to import Lock and RxSwift in to my project In my project, created by other, i have problems with some libraries that i'm "podding" them in my pod file, using cocoapod.
this is my pod file
# Uncomment this line to define a global platform for your project
platform :ios, "9.3"

target 'classme' do
    use_frameworks!
    inhibit_all_warnings!
    pod 'Firebase/Core'
    pod 'Firebase/Database'
    pod 'Firebase/Storage'
    pod 'Firebase/DynamicLinks'
    pod 'Firebase/Auth'
    pod 'Firebase/Messaging'
    pod 'Lock'
    pod 'RxSwift'
    pod 'RxCocoa'
    pod 'RxDataSources'
    pod 'Auth0'
    pod 'HockeySDK'
    pod 'MaterialControls'
    pod 'libPhoneNumber-iOS'
    pod 'SwiftLint'
    pod 'Mixpanel-swift'
    pod ‘AppsFlyerFramework’
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['SWIFT_VERSION'] = '3.0'
    end
  end
end

When trying to import the Lock i get the following message
No such module 'Lock'
Also for the RxSwift
How it can be solved?

A: I have used the myApp.xcworkspace instead of myApp.xcodeproj and the problem fixed.


Q: How can I mongoimport with Meteor? I made a mongoexport of some local data that I now want to mongoimport into production. I'm trying the following command:
mongoimport -h production-db-b2.meteor.io --port 27017 --username client --password password_that_expires_fast --collection collection_name --db prod_meteor_com --file ./mongo_import.json

This appears to be quite similar to the solution posted here: how to mongoimport data to deployed meteor app?
However, it's not working with the error couldn't connect to [production-db-b2.meteor.io:27017] couldn't connect to server production-db-b2.meteor.io:27017
How do I get around this?
(Note: I also tried concatenating the port and host into -h production-db-b2.meteor.io:27017 to no avail)

A: This is what worked for me in the past. I'm not exactly sure of why it works and your solution doesn't, but I think it has something to do with not specifying the collection or the file in a certain way.
mongoimport -u client -h production-db-b2.meteor.io:27017 -d myapp_meteor_com -p passwordthatexpiresreallyfast /pathtofile

A: check your port. the local meteor mongodb uses 3001 not 27017...
i'm using the following line successfully
mongoimport --host localhost:3001  -d meteor -c TestCollection --type csv --file /home/ubuntu/meteorMongoImportTest/results1.txt --headerline


Q: How to access a form inside a material step template in AngularDart? I am trying to combine a material-stepper with a form in AngularDart. The continue button from the material-stepper should be disabled as long as some required inputs are missing from the form. When the form is completed, the continue button should trigger a submit on the form.
However, as the step is a template, it creates its own scope and the reference to form cannot be used outside this scope. Therefore, the following code will not compile with error The getter 'form' isn't defined for the class....
<material-stepper>
    <template step
          name="Personal data"
          (continue)="form.submit()"
          [canContinue]="form.valid"
    >
        <form #form="ngForm">
            <material-input required
                            label="Name"
                            ngControl="name"
            ></material-input>
        </form>
        form complete: {{form.valid}}
    </template>
</material-stepper>

Is there another way to access the form or another solution to accomplish the same behavior?

A: The way that templates work is that the components aren't instantiated until they are needed. In this case you are asking for the state of a form before the form is added to the component tree.
In terms of what you could do I suggest following Gunter's answer in the comments:

I'd use a shared service that you provide in the component that
  contains above markup and add a component or directive to the
   that injects that service and communicates from the
  template with the parent using that service. The parent that provides
  the service needs also to inject it so that both communication ends
  have a reference to the same service instance. The service can use a
  stream to allow one (or both) party to emit events and the other to
  subscribe to them.


Q: How to remove 'My Approvals' tab from Approval screen (EP503010) in Acumatica? I am trying to remove My Approvals tab from Approval screen (EP503010). But challenge is its not like other pages. This screen built in with some automation steps and conditions. How to remove My Approval tab?

A: I found the solution for this question. We need to use filter in screen in top corner


Q: How to solve the constant to the negative gurobi variable power in python I am using Gurobi with Python to solve the following problem:

max. (1-Var(3^{-VC})) * (mean(VC)) s. t. sum(C) <= 3 and C in {0,1}

Whereas, C is a binary decision vector of length n. V is a coefficient (information) matrix of size mxn (m<=n). Here is my python code:
from gurobipy import *
import numpy as np

# EXAMPLE DATA SET
# ----------------------------------------------
V = np.matrix((
            (1,1,1,1,0,0),
            (0,1,1,1,1,0),
            (1,1,0,0,0,1),
            (0,0,0,1,1,1)))
V = V.tolist()

# LOCAL FUNCTIONS
# ----------------------------------------------

# V times C
def V_x_C(V,C):
    VC = {}
    for i in range(np.shape(V)[0]):
        ij_sum = 0;
        for j in range(len(C)):
            ij_sum +=  V[i][j]*C[j]
        VC[i] = ij_sum
    return VC

# Square
def sqr(vec):
    sqr_vec = {}
    for i in range(len(vec)):
        sqr_vec[i] = vec[i]*vec[i]
    return sqr_vec

# Variance
def variance(vec):
    mean_vec = sum(vec)/len(vec)
    diff_vec = vec-mean_vec
    sqdf_vec = sqr(diff_vec)
    var_vec  = (sum(sqdf_vec))/len(vec)
    return var_vec

# Power
def pwr(scalr,vec):
    reslt = {}
    for i in range(len(vec)):
        reslt[i] = scalr**vec[i]
    return reslt

# ObjVar
def objVar(V,C):
    VC = V_x_C(V,C)
    negVC = np.dot(-1,VC.values())
    pwrVC = pwr(3,negVC)
    varVC = variance(1-pwrVC)
    return varVC

# ObjMean
def objMean(V,C):
    VC = V_x_C(V,C)
    sumVC = 0
    for i in range(len(VC)):
        sumVC += VC[i]
    meanVC = float(sumVC)/len(VC)
    return meanVC

# OPTIMIZATION
# ----------------------------------------------

# Create a new model
m = Model("My Model")

# Optimization Variables
C = {}
for i in range(np.shape(V)[1]):
    C[i] = m.addVar(vtype=GRB.BINARY)

# The objective is to maximize the costs
m.modelSense = GRB.MAXIMIZE

# Integrate new variables
m.update()

# Objective Function
m.setObjective( (1-objVar(V,C))*(objMean(V,C)) )

# Constraint
m.addConstr( quicksum ([C[i] for i in range(np.shape(V)[1])]) <= 3)

m.optimize()

# Publish results
for v in m.getVars():
    print('%s %g' % (v.varName, v.x))

I am getting following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/asif/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 682, in runfile
    execfile(filename, namespace)
  File "/home/asif/anaconda/lib/python2.7/site-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile
    builtins.execfile(filename, *where)
  File "/media/Win7/DATA/MPS-GSMR/PLANNER/TestPython/question_gurobi_form.py", line 83, in <module>
    m.setObjective( (1-objVar(V,C))*(objMean(V,C)) )
  File "/media/Win7/DATA/MPS-GSMR/PLANNER/TestPython/question_gurobi_form.py", line 52, in objVar
    pwrVC = pwr(3,negVC)
  File "/media/Win7/DATA/MPS-GSMR/PLANNER/TestPython/question_gurobi_form.py", line 45, in pwr
    reslt[i] = scalr**vec[i]
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'LinExpr'

So apparently, the main issue is how to use gurobi variable as power on a constant. Please suggest me to address the bug in particular and the overall implementation in general.


Q: When creating a form in React .map() does not populate select > options correctly, but works for a normal div I am using React (and Redux) and have a form that I need to populate a dropdown with data via an API call.
When I use .map() within a standard div the list of results outputs correct. This is the code:
<div>
  {categories &&
    categories.map((category, i) => (
      <option
        key={i}
        label={category.categoryName}
        value={category._id}
        name={category.categoryName}
        category={category}
      >
        {category.categoryName}
      </option>
    ))}
</div>

When I then try and map the same data within a select/option dropdown it only renders the first result. i.e. there is no dropdown. Here's this code:
<select
          value={categoryName}
          onChange={(e) => setCategoryName(e.target.value)}
        >
          {categories &&
            categories.map((category, i) => (
              <option
                key={i}
                label={category.categoryName}
                value={category._id}
                name={category.categoryName}
                category={category}
              >
                {category.categoryName}
              </option>
            ))}

Here's the full code for the component in a github gist
Thanks in advance for any additional insight you can provide.
Edited to add in actions and reducer:
 export const getCategories = () => async (dispatch) => {
  try {
    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };
    const res = await axios.get(
      "http://localhost:5000/category/getallcategories",
      config
    );

    dispatch({
      type: GET_CATEGORIES,
      payload: res.data,
    });
    console.log("2222" + res.data);
  } catch (err) {
    dispatch({
      type: CATEGORY_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

And Reducer:
    export default function (state = initialState, action) {
  const { type, payload } = action;
  switch (type) {
    case GET_CATEGORIES:
      return {
        ...state,
        categories: payload,
        loading: false,
      };

A: <select> tag should contain the value. In your case it is the state: taskTitle. Onchange should also be under select.
In your code you use this useState:
const [taskTitle, setTaskTitle] = useState("");

So try to change the select to this:
<select
   value={taskTitle}
   onChange={(e) => setTaskTitle(e.target.value)}>
      {categories &&
      categories.map((category, i) => (
         <option
            key={i}
            label={category.categoryName}
            value={category._id}
            name={category.categoryName}
            category={category}
         >
           {category.categoryName}
         </option>
       ))}
</select>


Q: Highstock scrollbar not covering the whole length in multiple series I'm having an issue with the scrollbar in multiple series line chart where x-axis is date.
Looks like the max length of the scrollbar is determined by the length of the first (older) series.
Although when pressing the 'All' button in range selector I can see all of the series, as the first series ends before the others, as soon as I touch the scrollbar the chart readjusts so that all I can see is the data contained in the first series' length period.
After that, if I want to see the series after the first one has ended, I need to drag the chart or click the 'All' button in range selector again.
I would really appreciate any help you could provide.
Thanks in advance!
jsFiddle: http://jsfiddle.net/8DdP4/2/

A: Indeed, it's not supported to cover all series. Here you can find workarund.
With demo: http://jsfiddle.net/highcharts/SD4XN/
In short: in callback add series to the navigator on your own:
    function (chart) {
        chart.addSeries({
            data: seriesOptions[2].data,
            xAxis: 1,
            yAxis: 1
        });
    }

A: The scrollbar you refer to is called navigator.
There is a property in navigator called series which is defined as:

series: Object
Options for the navigator series. Available options are the same as
  any series, documented at plotOptions and series.
Unless data is explicitly defined on navigator.series, the data is
  borrowed from the first series in the chart.

You can see it here.
Im not sure if you can build your navigator from multiple series, i suppose it is posibles. In case it is not build build the navigator with the largest.


Q: How to get wallet of user if its delete once in hypeledger I need one help as I have confusion in one condition let's user register and enroll to the network and it's secret which is generate at time of registration saved in mongodb but somehow it's wallet got deleted so we need to register the user again or we can get wallet again just enroll user again with same secret?

A: Yes, you can enroll the Identity again using the same secret.  Assuming that the max number of enrollments has not been exceeded - but the default is "-1" (unlimited).
FYI each time you enroll you get different credentials, but they are valid for the same Identity.


Q: Avoid showing logger entries in console I have one "basic" logging configuration that logs to stdout in my project.
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)

SERVER_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(filename)s:%(lineno)d] %(message)s"
DATETIME_FORMAT = "%d/%b/%Y %H:%M:%S"

logging.basicConfig(
    level=logging.INFO,
    format=SERVER_FORMAT,
    datefmt=DATETIME_FORMAT,
    handlers=[stream_handler])

I have also another logger user_logger that should not print anything. Instead, it should store log entries in a variable.
user_logger = logging.getLogger('user_logger')
user_logger.setLevel(logging.INFO)

log_capture_string = io.StringIO()
log_capture_string_handler = logging.StreamHandler(log_capture_string)
log_capture_string_handler.setLevel(logging.INFO)

log_capture_string_handler.setFormatter(logging.Formatter(USER_FORMAT))
user_logger.handlers = [log_capture_string_handler]

The problem is that when I call:
user_logger.info('This should only be in "log_capture_string"')
it prints it to the console.
Do you know how to avoid that?

A: You should set user_logger.propagate = False. logging.propagate docs

If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.

So, your root logger will not send any data to stderr.
This example outputs nothing
import io
import logging

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)

SERVER_FORMAT = "[%(asctime)s] %(levelname)s [%(name)s:%(filename)s:%(lineno)d] %(message)s"
DATETIME_FORMAT = "%d/%b/%Y %H:%M:%S"

logging.basicConfig(
    level=logging.INFO,
    format=SERVER_FORMAT,
    datefmt=DATETIME_FORMAT,
    handlers=[stream_handler])

user_logger = logging.getLogger('user_logger')
user_logger.propagate = False
user_logger.setLevel(logging.INFO)

log_capture_string = io.StringIO()
log_capture_string_handler = logging.StreamHandler(log_capture_string)
log_capture_string_handler.setLevel(logging.INFO)

log_capture_string_handler.setFormatter(logging.Formatter(SERVER_FORMAT))
user_logger.handlers = [log_capture_string_handler]

user_logger.info('This should only be in "log_capture_string"')


Q: why does LedoitWolf return zeros for off-diagonal elements? from sklearn.covariance import EmpiricalCovariance, LedoitWolf

a = np.array([[ 0.6278, -1.1273 ],
              [ 0.2323,  0.4533  ],
              [ 0.3234, 1.5356 ],
              [1.7473 ,  -0.3113 ],
              [-0.3525 , 0.2577  ]])

Empirical_cov = EmpiricalCovariance().fit(a)
Empirical_cov.covariance_

array([[ 0.48009421, -0.23144627],
       [-0.23144627,  0.77341954]])

LedoitWolf_cov = LedoitWolf().fit(a)
LedoitWolf_cov.covariance_

array([[ 1., -0.],
       [-0.,  1.]])

Why is LedoitWolf giving me zeros for the off-diagonal elements? I have a few larger datasets in which this happens.
Is this a bug? The empirical covariance is non-zero, so shouldn't LedoitWolf also be non-zero? I read that using LedoitWolf would be slightly more accurate than empirical covariance, but what is the point if most covariance elements turn out to be zero?


Q: Mapping entity to dto with interfaces I've my entity class I retrieve from database:
public class User{
    public string Username {get; set;}
    public List<IAddress> Addresses {get; set;}
}

public class Address: IAddress{
    public string Line1 {get; set;}
    public string Line2 {get; set;}
}
public class AddressExtended:Address, IAddress{
    public string Line3 {get; set;}
    public string Line4 {get; set;}
}
public interface IAddress{
}

I use Automapper to map this entity to the mirrored DTO:
public class UserDto{
    [JsonProperty("username")]
    public string Username { get; set; }
    [JsonProperty("addresses")]
    public List<IAddressDto> Addresses { get; set; }
}

public class AddressDto: IAddressDto{
    [JsonProperty("line1")]
    public string Line1 { get; set; }
    [JsonProperty("line2")]
    public string Line2 { get; set; }
}
public class AddressExtendedDto:AddressDto, IAddressDto{
    [JsonProperty("line3")]
    public string Line3 { get; set; }
    [JsonProperty("line4")]
    public string Line4 { get; set; }
}
public interface IAddressDto{
}

Automapper configuration is the following:
CreateMap<IAddress, IAddressDto>();
CreateMap<Address, AddressDto>();
CreateMap<AddressExtended, AddressExtendedDto>();

The problem is that when I run my application, if in the entity I have 2 addresses and 1 addressExtended, in DTO the Addresses property () is mapped like this:
[
 {Proxy<MyProject.Models.Dto.IAddressDto_MyProject_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null>},
 {Proxy<MyProject.Models.Dto.IAddressDto_MyProject_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null>},
 {Proxy<MyProject.Models.Dto.IAddressDto_MyProject_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null>}
]

The Username property it is correctly valued.
What I miss?
UPDATE
I added a fiddler here:
https://dotnetfiddle.net/ZkUZgp

A: As per my knowledge, one approach solving the issue is using Construct using below code
cfg.CreateMap<Address, AddressDto>();
cfg.CreateMap<AddressExtended, AddressExtendedDto>();
cfg.CreateMap<IAddress, IAddressDto>().ConstructUsing((IAddress addressDto) =>
{
    if (addressDto is AddressExtended) return Mapper.Map<AddressExtendedDto>(addressDto);
    return Mapper.Map<AddressDto>(addressDto);
});

Edit 1:
Here is the final answer and it solves your problem
cfg.CreateMap<Address, AddressDto>();
cfg.CreateMap<AddressExtended, AddressExtendedDto>();
cfg.CreateMap<IAddress, IAddressDto>().ConstructUsing((addressDto, ctx) =>
{
    var destination = Mapper.Instance.ConfigurationProvider.GetAllTypeMaps()
                        .First(t => t.SourceType == addressDto.GetType());
    return ctx.Mapper.Map(addressDto, addressDto.GetType(), destination.DestinationType) as IAddressDto;
});

Instead of getting destination type using LINQ you can build a dictionary and get from it for faster execution.


Q: Encrypt and compress html-codes in iPhone app bundle, unpack on first start My client wants to encrypt/compress the html-code for their medical books in the iPhone bundle, to protect their IP.
Whats is a good way to prepare this file for the app bundle, and what complementary libraries (C, Obj-C) should I use to do the decryption and decompressing on the first launch of the app?
Copying the file to ~/Documents, then working on it seems like the best solution. Thoughts?

A: This is quite tricky... almost impossible to make it really unbreakable. Any reasonnably motivated person will be able to pierce through it. You'll only make it a little harder to do. In any case, you definitely can't store any secret key in the bundle itself. You'd need to securely obtain the decryption key over a secure channel from a server and use it as needed. Even then, someone doing jailbreak would probably be able to run GDB over your running program and extract the secret key in RAM + the secret key would be shared amongst all users of your app... You're essentially trying to implement a DRM scheme, which is inherently flawed by design... Unless you need offline access, you might want to pull the data as needed from a secure erver... at least you "could" throttle information leakage...

A: Here's a few thoughts.
If the book text is all alphanumeric data, then don't save the data as ASCII - save them in your own binary encoded format (for instance use 5 bits instead of 8 and pack into words). That gives you a bit of compression, slight obfuscation and a very cheap (in clock cycles) decompression. You would have a data format that is quick to access on the fly and will keep the casual curious hacker out of the text. Clock cycles would be my main concern and security second.
Another idea is store the decrypt key for a typical Blowfish encryption in obfuscated format in the app. Split into two or three constants that require some odd operation to restore for instance. But of course, now the overhead of Blowfish or whatever will be your concern.
Since you will not be able to implement perfect security (perfection is extremely expensive), the IP owners will have to use traditional copyright and trade secret techniques to fully protect their property. You've made it harder to hack, but it's still up to the lawyers to be diligent, just a book on the shelf in the reserved section of the library (no photocopies please!).
Cheers

A: I would keep the documents encrypted if I were you and just decrypt them as needed. One would easily be able to access the decrypted documents on a jailbroken device.
See the "Security Overview" document and the CryptoExercise sample code for encryption techniques

A: You probably won't like it, but the best way is to just not use HTML. Once you pass the decrypted HTML to UIWebView, it is very easy for a malicious user to steal it at that level, defeating any purpose your encryption algorithm had. A UIView subclass with custom drawing code and a custom encrypted backing format will be much more difficult to work around

A: From Mac OS X and iPhone OS Security Services:

You can use Keychain Services to
  encrypt and store small amounts of
  data (see Keychain Services Reference
  and Keychain Services Programming
  Guide). If you want to encrypt or
  decrypt larger amounts of data in Mac
  OS X, you can use the Common Security
  Services Manager (CSSM) Cryptographic
  Services Manager. This manager also
  has functions to create and verify
  digital signatures, generate
  cryptographic keys, and create
  cryptographic hashes. In iPhone OS,
  the Certificate, Key, and Trust
  Services API provides functions for
  generating encryption keys, creating
  and verifying digital signatures, and
  encrypting blocks of data; see
  Certificate, Key, and Trust Services
  Reference.

It's always a choice between performance (encryption just doesn't come free) and security (security and everything else, really).  But what else is new?  If you keep the individual files small enough, maybe decryption doesn't slow you down much.  Alternatively, you may consider predictive decryption such that you have certain files being decrypted in the background, say those linked from the currently viewed file, etc.  I realize, however, that concurrancy on the iPhone may be pretty spotty (I don't know as I haven't dropped the cash for a license).  You may also realize performance gains by only encrytping those files that really need it; does an index/table of contents or other often accessed file really need to be encrypted?  Does that count as IP your client is worried about?

A: For compression I can recommend QuickLZ (fastest engine I saw, great compression ratio).


Q: Selecting all foreign key references on table I need to select all foreign key references on a table. I came up with a query that works, but takes 9 seconds to execute. It would be very nice if someone could help with optimizing it. Thank you very much!
Here is the query:
SELECT A.TABLE_NAME REFENCING_TABLE,
       A.COLUMN_NAME REFENCING_COLUMN,
       B.TABLE_NAME REFERENCED_TABLE,
       B.COLUMN_NAME REFERENCED_COLUMN
  from (select TABLE_NAME,
               COLUMN_NAME,
               REFERENCED_CONSTRAINT_NAME,
               POSITION
          from all_cons_columns C
          join (select CONSTRAINT_NAME,
                       PK.REFERENCED_CONSTRAINT_NAME
                  from all_constraints FK
                  JOIN (select CONSTRAINT_NAME REFERENCED_CONSTRAINT_NAME
                          from all_constraints
                          where constraint_type in ('P','U') and
                                table_name = :tablename) PK
                    on FK.R_CONSTRAINT_NAME = PK.REFERENCED_CONSTRAINT_NAME
                  where constraint_type = 'R') FK
            on C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME) A
  join (select TABLE_NAME,
               COLUMN_NAME,
               CONSTRAINT_NAME,
               POSITION
          from all_cons_columns) B
    on REFERENCED_CONSTRAINT_NAME = B.CONSTRAINT_NAME AND
       A.POSITION = B.POSITION;

A: You may use this query to find all foreign key references on a table:
SELECT
fk.owner fk_schema_owner,fk.table_name fk_table,
fk.column_name fk_column, fk.constraint_name fk_constraint_name,
pk.r_owner pk_schema_owner,
c_pk.table_name pk_table_name, c_pk.constraint_name pk_constraint_name
FROM
all_cons_columns fk
  JOIN all_constraints pk
     ON fk.owner = pk.owner AND fk.constraint_name = pk.constraint_name
  JOIN all_constraints c_pk
     ON pk.r_owner = c_pk.owner AND pk.r_constraint_name = c_pk.constraint_name
  WHERE pk.constraint_type = 'R' AND fk.table_name = :InputTableName


Q: How to generate non-repeating Random Numbers in Unity I am trying to create a simple Bingo game and want to make sure the numbers are not repeating on the bingo card. I have a random number generator, but for some reason the code I'm using doesn't work as the same numbers will constantly repeat. Could somebody please take a look at my code below and either tell me what I need to fix or fix the code for me?
public Grid(int width, int height, float cellSize)
{
    this.width = width;
    this.height = height;
    this.cellSize = cellSize;

    gridArray = new int[width, height];
    debugTextArray = new TextMesh[width, height];
    for (int x = 0; x < gridArray.GetLength(0); x++)
    {
        for (int y = 0; y < gridArray.GetLength(1); y++)
        {
            debugTextArray[x, y] = UtilsClass.CreateWorldText(gridArray[x, y].ToString(), null, GetWorldPosition(x, y) + new Vector3(cellSize, cellSize) * .5f, 20, Color.white, TextAnchor.MiddleCenter);
            Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x, y + 1), Color.white, 100f);
            Debug.DrawLine(GetWorldPosition(x, y), GetWorldPosition(x + 1, y), Color.white, 100f);
        }
    }
    Debug.DrawLine(GetWorldPosition(0, height), GetWorldPosition(width, height), Color.white, 100f);
    Debug.DrawLine(GetWorldPosition(width, 0), GetWorldPosition(width, height), Color.white, 100f);

    for (int x = 0; x <= 4; x++)
    {
        RandomValue(0, x);
        RandomValue(1, x);
        RandomValue(2, x);
        RandomValue(3, x);
        RandomValue(4, x);
    }

}

private Vector3 GetWorldPosition(int x, int y)
{
    return new Vector3(x, y) * cellSize;
}

public void RandomValue(int x, int y)
{

    if (x >= 0 && y >= 0 && x < width && y < height)
    {
        list = new List<int>(new int[Lenght]);

        for (int j = 0; j < 25; j++)
        {

            Rand = UnityEngine.Random.Range(1, 50);

            while (list.Contains(Rand))
            {
                Rand = UnityEngine.Random.Range(1, 50);

            }

            list[j] = Rand;
            gridArray[x, y] = list[j];
        }

        debugTextArray[x, y].text = gridArray[x, y].ToString();
        debugTextArray[2, 2].text = "Free";
    }
}

A: As mentioned in the comment on your question, it's probably the easiest to just shuffle the numbers in the range [1,50] and then take the first 25 or however many you want.
The reason your code isn't working properly and you see a lot of repeats is because you're calling the RandomValue() function multiple separate times and the list variable you're comparing against if a value is already on the chart is inside of that function. Meaning that it will only ever check the values it has generated in that call, in this case meaning only for one row.
Also, if you make a list that you know will always be the same size, you should use an array instead. Lists are for when you want the size to be adjustable.
Solution 1:
A very simple way to generate an array with the numbers 1-50 would be to do this:
//Initialize Array
int[] numbers = new int[50];
for (int i = 1; i <= numbers.Length; i++)
{
    numbers[i] = i;
}

//Shuffle Array
for (int i = 0; i < numbers.Length; i++ )
{
    int tmp = numbers[i];
    int r = Random.Range(i, numbers.Length);
    numbers[i] = numbers[r];
    numbers[r] = tmp;
}

//Get first 'n' numbers
int[] result = Array.Copy(numbers, 0, result, 0, n);
return result;

I'm not sure if it's the most efficient way, but it would work.
Solution 2:
To change your code to check against the entire list, I would change this section:
for (int x = 0; x <= 4; x++)
{
    RandomValue(0, x);
    RandomValue(1, x);
    RandomValue(2, x);
    RandomValue(3, x);
    RandomValue(4, x);
}

To something like this:
List<int> values = new List<int>();
for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {
        int r = RandomValue(1, 50);
        while (values.Contains(r))
        {
            r = RandomValue(1, 50);
        }
        values[y * width + x].Add(r);
        gridArray[x, y] = r;
    }
}

int RandomValue(int min, int max) {
    return UnityEngine.Random.Range(min, max);
}

Hope this helps!

A: Basically your concept in function RandomValue() is correct, but problem is it only check in same column, so you have to bring the concept of RandomValue() to Grid() level. You need a List contain all approved value, then check Contains() at Grid().
But in fact you can do it in all one go.
Make sure your width*height not larger than maxValue.
Dictionary<Vector2Int, int> CreateBingoGrid(int width, int height, int maxValue)
{
    var grid = new Dictionary<Vector2Int, int>();
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            var num = Random.Range(1, maxValue);
            while (grid.ContainsValue(num))
            {
                num = Random.Range(1, maxValue);
            }
            grid.Add(new Vector2Int(x, y), num);
        }
    }
    return grid;
}


Q: error- dalvik.system.PathClassLoader [data/app/com.my.appname-2.apk] I searched a lot for similar kind of error, but I am not getting a solution for it. I am getting this error as soon as I start the app
03-21 10:33:08.100: E/AndroidRuntime(13098): FATAL EXCEPTION: main
03-21 10:33:08.100: E/AndroidRuntime(13098): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.airlife/com.example.airlife.MainActivity}: java.lang.ClassNotFoundException: com.example.airlife.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.airlife-2.apk]
03-21 10:33:08.100: E/AndroidRuntime(13098):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1785)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1893)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at android.app.ActivityThread.access$1500(ActivityThread.java:135)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1054)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at android.os.Looper.loop(Looper.java:150)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at android.app.ActivityThread.main(ActivityThread.java:4389)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at java.lang.reflect.Method.invokeNative(Native Method)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at java.lang.reflect.Method.invoke(Method.java:507)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at dalvik.system.NativeStart.main(Native Method)
03-21 10:33:08.100: E/AndroidRuntime(13098): Caused by: java.lang.ClassNotFoundException: com.example.airlife.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.airlife-2.apk]
03-21 10:33:08.100: E/AndroidRuntime(13098):    at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at android.app.Instrumentation.newActivity(Instrumentation.java:1040)
03-21 10:33:08.100: E/AndroidRuntime(13098):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1777)
03-21 10:33:08.100: E/AndroidRuntime(13098):    ... 11 more

MainActivity.java is like this
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends MapActivity implements OnClickListener{

    private ImageButton mVid,mAgebtn,mWeightbtn,mPicbtn,mMsgbtn,mReqbtn,mHelibtn,mDocbtn,mContextbtn;

    private MapView mapView;

    private MyLocationOverlay myLocationOverlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          mapView = (MapView)findViewById(R.id.webview);

          mapView.setBuiltInZoomControls(true);
          myLocationOverlay = new MyLocationOverlay(this, mapView);

          mapView.getOverlays().add(myLocationOverlay);
            mapView.postInvalidate();
            // call convenience method that zooms map on our location
            zoomToMyLocation();

        mAgebtn = (ImageButton) findViewById(R.id.imageView36);
        mWeightbtn = (ImageButton) findViewById(R.id.imageView4);
        mPicbtn = (ImageButton) findViewById(R.id.imageView5);
        mMsgbtn = (ImageButton) findViewById(R.id.imageView6);
        mReqbtn = (ImageButton) findViewById(R.id.imageView32);
        mHelibtn = (ImageButton) findViewById(R.id.btnsearch);
        mDocbtn = (ImageButton) findViewById(R.id.btnprovide);
        mVid = (ImageButton) findViewById(R.id.btnpost);
        mContextbtn = (ImageButton) findViewById(R.id.btnsettings);

         mAgebtn.setOnClickListener(this);
         mWeightbtn.setOnClickListener(this);
         mPicbtn.setOnClickListener(this);
         mMsgbtn.setOnClickListener(this);
         mReqbtn.setOnClickListener(this);
         mHelibtn.setOnClickListener(this);
         mDocbtn.setOnClickListener(this);
         mVid.setOnClickListener(this);
         mContextbtn.setOnClickListener(this);

    }

     @Override
        protected void onResume() {
            super.onResume();
            // when our activity resumes, we want to register for location updates
            myLocationOverlay.enableMyLocation();
        }

        @Override
        protected void onPause() {
            super.onPause();
            // when our activity pauses, we want to remove listening for location updates
            myLocationOverlay.disableMyLocation();
        }

        /**
         * This method zooms to the user's location with a zoom level of 10.
         */
        private void zoomToMyLocation() {
            GeoPoint myLocationGeoPoint = myLocationOverlay.getMyLocation();
            if(myLocationGeoPoint != null) {
                mapView.getController().animateTo(myLocationGeoPoint);
                mapView.getController().setZoom(10);
            }
            else {
                Toast.makeText(this, "Cannot determine location", Toast.LENGTH_SHORT).show();
            }
        }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.airlife"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

       <uses-permission android:name="android.permission.WRITE_SETTINGS" />
         <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.airlife.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
          <activity android:name=".playvid" />
          <activity android:name=".Display" />
          <activity android:name=".Video" />
           <activity android:name=".Documents" />
                 <activity android:name=".Contact" />
                 <activity android:name=".FixedMyLocationOverlay" />

    </application>

</manifest>

Please tell me why I am getting this error, and how to solve this.

A: Got the solution. I had missed this code in my manifest file
    <uses-library android:name="com.google.android.maps"/>

A: Class not found exception in MainActivity.
I think you've the wrong package, or that your APK doesn't have what you think it has.This is your package name.
com.example.airlife

Maku sure that it is imported in all activities as.
package com.example.airlife;

and don't forget to add entry in manifest file for every new activity.
If so, then make this change in manifest file. No need to mention your package name and remove allowBackUp
<activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

A: if not this try adding any library files you are using. missing library files may also cause this exception. see this link
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo after SDK update


Q: restart specific website in IIS6 via command line Does anyone know if I can restart a specific website within IIS 6 using the command line.
I don't want to use a blanket IISReset /restart command if I can avoid it.
I have a site that has an issue and is maxing out the server, I need to find a fix for it but in the meantime I also want to sleep so I'd like to just restart it every 10 minutes overnight to nurse it through.

A: Sounds like you actually want to recycle an Application pool rather than stop/start a website.
To do this you can use the IISAPP.vbs utility:

cscript c:\windows\system32\iisapp.vbs /a "My AppPool" /r

You can run the utility with a /? flag for full usage details and some sample commandlines.
If you really want to start/stop a website you can use the ADSUTIL.vbs utility:

cscript c:\inetpub\adminscripts\adsutil.vbs STOP_SERVER W3SVC/1
cscript c:\inetpub\adminscripts\adsutil.vbs START_SERVER W3SVC/1

For more information on ADSUTIL.vbs please see this page :
Using the Adsutil.vbs Administration Script (IIS 6.0)


Q: Panel does not appear I have a panel with a really simple config:
Ext.define('MyApp.view.PanelPersonalData', {
extend: 'Ext.Panel',
alias: 'widget.panelpersonaldata',

requires: [
    'Ext.Panel',
    'Ext.Button',
    'Ext.XTemplate'
],

config: {
    items: [
        {
            xtype: 'panel',
            styleHtmlContent: true,
            items: [
                {
                    xtype: 'panel',
                    tpl: [
                        'Data:',
                        '{salutation} {firstname} {lastname}
',
                        'Birthday: {birthday}
',
                        '{street} {number}
',
                        '{zip} {city}
',
                        'E-Mail: {email}',
                        '
Insurance: {priorInsurance}
',
                        '
',
                        'IBAN: {iban}
',
                        'BIC: {bic}',
                        '
',
                        '
Job: {occupationGroup}
'
                    ]
                }
            ]
        }
    ]
}

The data for the placeholders is set correctly (I made a console log of it). But the pannel won't appear on the screen. If I remove the tpl config and add html: 'TEST' instead, I can see the correct output of TEST. What am I doing wrong here with the tpl config?

A: The problem was that I called setData() for the wrong panel. Instead of setting it to the panel with the placeholders, I used the parent panel. After changing this, everything works fine now.


Q: When do you need to use type annotations? While reading Data Types from the Rust Book I noticed that sometimes a variable is defined with a type annotation and sometimes not.
When should I use type annotations?
let tup: (i32, f64, u8) = (500, 6.4, 1);

let tup = (500, 6.4, 1);

let months = ["January", "February", "March", "April", "May", "June", "July",
              "August", "September", "October", "November", "December"];

let a: [i32; 5] = [1, 2, 3, 4, 5];

A: When types have to be specified
If the compiler cannot infer the type by itself, it must be specified:
let numbers: Vec<_> = (0..10).collect();

Types also cannot be omitted from items. In particular, consts and statics look very much like let statements, but the type must be specified:
const PI_SQUARED: i32 = 10;

// Not valid syntax
const HALF_PI = 1.5;

When types cannot be specified
When the type is anonymous, it cannot be specified
fn displayable() -> impl std::fmt::Display {
    ""
}

fn main() {
    let foo = displayable();

    // Not valid syntax:
    let foo: impl std::fmt::Display = displayable();
}

When the types can be specified, but do not have too
But most of the time, the type can be specified but doesn't have to: The compiler can infer it from usage.
In Rust, it is usually considered good practice to omit simple types when they can. The bound where people will decide that something is not simple anymore and decide that it must be specified or not is however very opinion-based and out of scope for StackOverflow.


Q: React Router Dom redirects incorrectly upon building Goal:  Reach http://localhost:3000/test.html?test=5
Problem:  When run in development mode and prior to building, I can reach http://localhost:3000/test.html?test=5 just fine.  However, after running 'react-scripts build', when navigating to http://localhost:3000/test.html?test=5, the page will redirect to http://localhost:3000/test with a status code 301 Moved Permanently.
App.js
import React from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import Test from "./Test";

function App() {
  return (
    <React.Fragment>
      <Router>
        <Route path="*" component={Test} />
      </Router>
    </React.Fragment>
  );
}

export default App;

Test.js
import React, { Component } from 'react';

class Test extends Component {

  render() {
    return (
      <React.Fragment>
        <h1>{this.props.location.pathname+this.props.location.search}</h1>
      </React.Fragment>
    );
  }
}

export default Test;

I believe it has something to do with the URL containing '.html?'.  When I try to navigate to 'http://localhost:3000/test.html/test=5', it works just fine, but as soon as you try 'http://localhost:3000/test.html?test=5', it will redirect to 'http://localhost:3000/test'
I created a demo of the problem if anyone wants to test it.
Demo


Q: how to put procedure inside package I have a package:
CREATE OR REPLACE PACKAGE pack1
AS
PROCEDURE details;
END pack1;
/
CREATE OR REPLACE PACKAGE BODY pack1
AS
    CREATE OR REPLACE PROCEDURE details
    IS
    BEGIN
    select *
    FROM table1;
    END details;
END;
/

But I am getting error message
Warning: Package Body created with compilation errors.

I am new to pl/sql, and trying to learn how to use package and procedure. I know my code might be far from correct. Tell me what changes i can do in my code to make it work

A: Use
PROCEDURE details

instead of
CREATE OR REPLACE PROCEDURE details

https://docs.oracle.com/cd/E11882_01/appdev.112/e25519/packages.htm#LNPLS00905
On the other hand, the SELECT statement needs a INTO statement. So the code could be:
CREATE OR REPLACE PACKAGE pack1
AS
  PROCEDURE details;
END pack1;
/
CREATE OR REPLACE PACKAGE BODY pack1
AS
  PROCEDURE details
  IS
    l_rec  table1%ROWTYPE;
  BEGIN
    SELECT *
      INTO l_rec
      FROM table1;
  END details;
END pack1;


Q: insert not functioning mysql php i got one problem with this . everytime i go insert it the page just refresh and blank. i dont know where is the problem but i checked my sql the data i use is the same. so i dont know where the problem is.
                      <form enctype="multipart/form-data" method="POST">

                         Generic Name:<input type="text" class="form-control" name = "gname">

                         Brand Name:<input type="text" class="form-control" name = "bname">

                         Quantity:<input type="number" min="0" class="form-control" name = "mqty">

                         Description:<input type="text" class="form-control" name = "mdesc">

                         <input type="submit" class="btn btn-info" name="add" Value="Add">

               </form>

                <?php
                include "../../functions/connect.php";
                error_reporting(0);

                    date_default_timezone_set('Singapore');
                    $date = date('m/d/Y h:i:s a', time());

                    ?>

                    <?php
                    include "../../functions/connect.php";
                    extract($_POST);

                    if(isset($add)){

                        $sql = "INSERT INTO `tbl_meds`(`date`,`generic`,`brand`,`description`,`medqty`) VALUES ('$date','$gname','$bname','$mdesc','$mqty')";
                        $result = mysql_query($sql) or die("Verification Error: " . mysql_error());

                    }

            ?>

EDIT: Result of var_dump($_POST) -
array(5) {
    ["gname"]=> string(11) "Paracetamol"
    ["bname"]=> string(8) "Biogesic"
    ["mqty"]=> string(3) "100"
    ["mdesc"]=> string(71) "The most prescribed Headache and Fever brand that's Effective and Safe."
    ["add"]=> string(4) "Save"
 }

A: if(isset($_POST["add"])){

this will work for you
your form has POST method. So on PHP side you have to handle it with $_POST global variable.


Q: Postfix - Html emails contain random characters I'm storing my postfix emails into mysql.
I notice some weird characters showing up in some messages, while other emails don't have them.  So, it's random.
Here's what I see:
--1001534069-1142425087-1366837456=:47630
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

=0A=0AConfirmation: We received your membership (one-year) p=
ayment  =0A=0A   =0A =0A =0A  =0A =0A =0A =0A=0A Confirmation:: We received =
your membership (one-year) payment=0AHi John Smith,=0AWe re=
............

--1001534069-1142425087-1366837456=:47630
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable

=0A
=0A    =
  =0A      <title>Confirmation: We received your membership=
............................

I included both content-types, and the weird characters are rather noticable.
I'm saving each email into a column type: text, with a Collation: utf8_unicode_ci
And for those interested in what I'm using to extract my postfix emails, I'm using the PHP imap_* functions.
Anyways, does anyone know why those weird characters get interjected?  (while other emails have perfect html or plain text?)

A: That's quoted printable encoding. You need to undo the content-transfer-encoding, which might be quoted printable or base64.


Q: Show all capes/products when i filter them through price range // React imports
import { useCallback, useEffect, useState } from 'react'

import { GetServerSideProps } from 'next'
import Link from 'next/link'
import { ParsedUrlQuery } from 'querystring'
import { capesApi } from 'api'
import {
    CapeCategoryEnum,
    CapeTypeEnum,
    GetCapesResponse
} from 'mantle-api-client'

// Component imports
import { ShopLayout } from '@components/Shop/ShopLayout'
import { Container, Text } from '@components/utils'
import { Pagination } from '@components/Pagination'
import { useRouter } from 'next/router'
import { RenderedMineman } from '@components/RenderedMineman'
import { capeTypes, capeCategories } from 'config'
import Checkbox from '@components/Checkbox/Checkbox'
import { toDollars } from '@helper/price'

// Types
interface Props {
    query: ParsedUrlQuery
    capeData: GetCapesResponse
}

/**
 * The MVP shop page. This is a public page.
 */
const Shop = ({
    capeData: initialCapeData,
    query: { page: initialPage }
}: Props) => {
    /**
     * State
     */
    const [page, setPage] = useState(initialPage ? Number(initialPage) : 1)
    const [capeData, setCapeData] = useState(initialCapeData)
    const [fetching, setFetching] = useState(false)
    const [filterCategories, setFilterCategories] = useState<CapeCategoryEnum[]>([])
    const [filterTypes, setFilterTypes] = useState<CapeTypeEnum[]>([])

    /**
     * Helpers
     */

    // Access the router.
    const router = useRouter()

    // This helper will add or remove selected categories to the categories state.
    const addOrRemoveCategoryToFilter = (categoryValue: CapeCategoryEnum) => {
        if (filterCategories.includes(categoryValue)) {
            setFilterCategories(
                filterCategories.filter((value) => value !== categoryValue)
            )
        } else {
            setFilterCategories(filterCategories.concat(categoryValue))
        }
    }

    // This helper will add or remove selected types to the types state.
    const addOrRemoveTypesToFilter = (typeValue: CapeTypeEnum) => {
        if (filterTypes.includes(typeValue)) {
            setFilterTypes(filterTypes.filter((value) => value !== typeValue))
        } else {
            setFilterTypes(filterTypes.concat(typeValue))
        }
    }

    const { capes, totalPages, count } = capeData

    // This client-side helper will fetch additional capes depending on filters passed to it.
    const fetchCapes = useCallback(
        async (page: number) => {
            setPage(page)
            setFetching(true)

            const capesDataR = (
                await capesApi.getCapes({
                    page,
                    sortBy: 'createdAt DESC',
                    categories: filterCategories,
                    types: filterTypes
                })
            ).data

            setCapeData(capesDataR)
            setTimeout(() => setFetching(false), 100)
        },
        [filterCategories, filterTypes]
    )

    // This helper will perform a client-side re-render of the page.
    const handlePageChange = (page: number) => {
        router.push(`/shop?page=${page}`, undefined, { shallow: true })
    }

    // Whenever the route changes or if we are fetching more capes, make sure to fetch more capes.
    useEffect(() => {
        fetchCapes(router.query.page ? Number(router.query.page) : 1)
    }, [router.query, fetchCapes])

    const[checkVal1, setCheckVal1]= useState(false);
    const[checkVal2, setCheckVal2]= useState(false);
    const[checkVal3, setCheckVal3]= useState(false);
    const[checkVal4, setCheckVal4]= useState(false);
    const[checkVal5, setCheckVal5]= useState(false);

this handleCheckData ftn returns the filtered data of only 1 page. meaning if I click the checkbox of price range >2$ it will show the prices >2$ on page 1 only and not rest of the products and i have to go to page 2 to see the rest of the filtered products
    const handleCheckData=(cape:any)=>{

        if(checkVal1===true){
            return cape.price>=1
        }
        else if(checkVal2===true){
            return cape.price>=200 && cape.price<=300
        }
        else if(checkVal3===true){
            return cape.price>=300 && cape.price<=400
        }
        else if(checkVal4===true){
            return cape.price>=400 && cape.price<=500
        }
        else if(checkVal5===true){
            return cape.price<=500
        }
        else{
            return cape.price>=0
        }

    }

    return (
        <>
            <Container>
                <ShopLayout>

                            {/* sidebar*/}

                                                <Text as='h4' tag='h2'>
                                                    Filter Capes
                                                </Text>

                                            <Text as='h4' tag='h2'>
                                                Price
                                            </Text>

                                        {/* 2nd: make the price checkbox a separate component */}

                                            {/* 1st checkbox */}

                                                 {'>'} $1.99
                                                <input type='checkbox' onClick={()=>setCheckVal1(!checkVal1)} />

                                            {/* 2nd checkbox */}

                                                $2.00 - $2.99
                                                <input type='checkbox' onClick={()=>setCheckVal2(!checkVal2)}/>

                                            {/* 3rd checkbox */}

                                                $3.00 - $3.99
                                                <input type='checkbox' onClick={()=>setCheckVal3(!checkVal3)}/>

                                            {/* 4th checkbox */}

                                                $4.00 - $4.99
                                                <input type='checkbox' onClick={()=>setCheckVal4(!checkVal4)}/>

                                            {/* 5th checkbox */}

                                                 {'<'} $5.00
                                                <input type='checkbox' onClick={()=>setCheckVal5(!checkVal5)}/>

                    {/*filtering by categories */}

                                            <Text as='h4' tag='h2'>
                                                Categories
                                            </Text>

                                            {capeCategories.map(
                                                ({ name, value }) => (

                                                        <Checkbox
                                                            labelClassName='text-sm text-gray-400 mr-4'
                                                            label={name}
                                                            handleClick={() =>
                                                                addOrRemoveCategoryToFilter(value)
                                                            }
                                                            className={`bg-gray-800 text-gray-400 rounded border border-stone-200 space-x-3 ${
                                                                filterCategories.includes(value)
                                                            }`}
                                                        />

                                                )
                                            )}

                  {/*filtering by types*/}

                                            <Text as='h4' tag='h2'>
                                                Types
                                            </Text>

                                            {capeTypes.map(({ name, value }) => (

                                                    <Checkbox
                                                        labelClassName='text-sm text-gray-400 mr-4'
                                                        label={name}
                                                        handleClick={() =>addOrRemoveTypesToFilter(value)
                                                        }
                                                        className={`bg-gray-800 text-gray-400 rounded border border-stone-200 space-x-3 ${
                                                            filterTypes.includes(value)
                                                        }`}
                                                    />

                                            ))}

the capes we will show plus the price filter ftn

                            {capes.filter((cape) => handleCheckData(cape)).map((cape) => (

                                                    <RenderedMineman
                                                        capes={[cape]}
                                                        rotation={
                                                            cape.type ===
                                                            CapeTypeEnum.Cape
                                                                ? 'back'
                                                                : 'front'
                                                        }
                                                    />

                                                    <Text
                                                        as='h3'
                                                        tag='h3'
                                                        className='text-current'
                                                    >
                                                        {cape.name}
                                                    </Text>

                                                    <Text as='h4' tag='p'>
                                                        ${toDollars(cape.price)}
                                                    </Text>

                                        </Link>

                                ))}{' '}

                {/* This pagination allows users to filter through pages of products. */}
                <Pagination
                    handlePageChange={handlePageChange}
                    pages={totalPages}
                    currentPage={page}
                    count={count}
                    perPage={16}
                    fetching={fetching}
                    displayNumberOfItems={false}
                />
            </ShopLayout>
        </Container>
    </>
)}

export const getServerSideProps: GetServerSideProps = async ({ query }) => {
    const capeData = (
        await capesApi.getCapes({
            page: query.page ? Number(query.page) : 1,
            sortBy: 'createdAt DESC'
        })
    ).data

    return {
        props: {
            query,
            capeData
        }
    }
}

export default Shop


Q: String returned by pyodbc different than a normal string? I used pyodbc to get some data from an mssql db. The returned text contains \n whenever a newline is necessary. I loaded all the text into the "row" variable.
var=row.somecolumnfromdatabase
var2=str('Some text\nand the newline.')

print(RichText(var))
print(RichText(var2))

However, if I use a function like RichText (from docxtpl) to transform the string, I receive different results. In the case of "var" (text loaded from db), the \n symbol is preserved. In the case of var2 (where I input the text by hand), the \n is transformed correctly. Simply printing var and var2 without transformations shows no difference and I would expect the contained strings to be identical - e.g. the RichText function should receive the exact same input.
What am I missing?


Q: Unable to I to display the list value in dropdown which I am passing as list from my java class in my JSP.My code works perfectly if I am using table I am passing list from my java class in my JSP where I want to display the list value in dropdown.
While debugging I checked that the list is containing desired values but not displaying in my JSP dropdown.
Though the values are coming if I am displaying in Table form.
Please, tell me where I am going wrong and how can I make my code to work?
Java Code:
    // add the event list to the model
    theModel.addAttribute("event", theEvents);
    return "fundContributionCollectionListPage";

JSP Code:
    <select name="eventSelected">
    <c:forEach var="tempEvents" items="${event}">
      <option value="tempEvents.eventName">${tempEvents.eventName}</option>
    </c:forEach>
    </select>


Q: how send tinymce content using jquery method post I had a form.
like this
<form id=form ><input type='text' name='input1'  ><textarea name='text' ></textarea></form>

when I do this
var $dados = $("#form").serialize()

I get all the values, to send via jquery post like this
       $.ajax({
            url: "action.php",
            data:  $dados,
            type: 'POST',
            timeout: 6000,
            success: function (retorno) {

            }
        });

The beginning of the problem is, my textarea is a TinyMCE, and I get the val using this
 $("#form").find('textarea').each(function(){
        $dados = $dados + "&" + $(this).attr('name') + "=" +  tinyMCE.get( $(this).attr('id') ).getContent();

    });

My variable $dados is something likes this
field=value & filed2 = value ....

Now the problem..
when I put a text like this
"Olá mundão"
My value of the TinyeMCE is (whit the spaces to show ) Ol & #xE1; Mund &#xE3 ;o
The value is a value with HTML entity
So, I have this particular caracter "&" in the tinyMCE value.
and my variable $dados become like this
input1=value & input2 = val & ue

This particular caracter makes mess with my tinyMCE value,
So someone can help me?

A: Why don't you use something like this to generate your $dados object?
There is no need to build your data as a html ajax GET Parameter string.
var $dados = {};
$("#form").find('textarea').each(function(){
    $dados[$(this).attr('name')] = tinyMCE.get($(this).attr('id')).getContent();
});