text:
Q: How to expand path from given argument using regular expression? I'm working on a simple search tool. It searches through source code files in directory defined by command line argument, for example:
finder 'path' 'keyword'

I have difficulties with how to properly transform given argument to a path string which I can use in Dir.chdir(path). Here is what I mean, according to my logic I have 4 distinct cases:

*

*.  (just current directory)

*/folder

*./folder

*~/Desktop/folder

Here is what I have now:
def expand_path(path)
  case path
  when '.'
   return '.'
  when /\/[a-z]*/.match(path)
   return Dir.pwd + path
  when /\.\/[a-z]*/.match(path)
   return Dir.pwd + path[1..-1]
  when /~(\/[a-zA-Z\w]*)+/.match(path)
   return File.expand_path(path, __FILE__)
  else
   puts "Wrong path name"
  end
end

I am not sure if there is a better approach, this is what I came up with.
Still, my approach doesn't work. I'm not sure if there is a problem with regex or with something else. I'm a newcomer in Ruby world so, may be I just made some silly mistake.
[SOLVED]
  def expand_path(path)
   case path
   when '.'
     return '.'
   when /~(\/[a-zA-Z\w]*)+/
     return File.expand_path(path, __FILE__)
   when /\.\/[a-z]*/
     return Dir.pwd + path[1..-1]
   when /\/[a-z]*/
     return Dir.pwd + path

   else
     puts "Wrong path name"
   end
  end

A: Thpugh as you say the issue has been solved, there is at least 1 point that can be improved in your regular expressions, namely [a-zA-Z\w] can be just replaced with mere \w as it already includes a-zA-Z.
From regular-expressions.info:

\w stands for "word character". It always matches the ASCII characters
  [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

Also, your last when contains /\/[a-z]*/ regex that also matches just /. If that is what you want, OK, if not, replace * with +. The same is with /\.\/[a-z]*/ - it will match ./. If you want to match ./ + at least 1 character, you need to replace adterisk with a plus.
So, I suggest:
def expand_path(path)
   case path
   when '.'
     return '.'
   when /~(\/\w*)+/
     return File.expand_path(path, __FILE__)
   when /\.\/[a-z]+/
     return Dir.pwd + path[1..-1]
   when /\/[a-z]+/
     return Dir.pwd + path

   else
     puts "Wrong path name"
   end
  end


text:
Q: Is it possible to integrate this equation? I need to integrate left side of this equation
$$r \left( \left(B \, \mathrm{ln}\dfrac{r}{R_2} +D \right) ^ \dfrac{-a}{a+1} + \left(F \, \mathrm{ln}\dfrac{r}{R_2} +D \right) ^ \dfrac{-a+1}{a+1}\right)\mathrm{d}r = ...$$
Where contants are $B, D, R_2, a, F$. Is it possible to express on some way these parts with exponents? In order to integrate it is necessary to first do this, then to integrate.
Or do I need to integrate numerical?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove duplicate link from add_menu_page In the theme admin menu below, the "MyTheme Menu Label" is being duplicated twice on the sidebar menu, once for the main menu link and again for the first submenu link.
How can I remove the 2nd instance of the link
add_menu_page(
    "MyTheme",
    "MyTheme Menu Label", //THIS IS REPEATED TWICE IN THE MENU
    "edit_themes",
    "functions.php",
    'theme_admin',
    get_bloginfo('template_directory') .'/img/favicon.png',31
);

add_submenu_page(
    'functions.php',
    "SEO Options",
    "SEO",
    'edit_themes',
    'my-seo-options',
    'theme_admin'
);

add_submenu_page(
    'functions.php',
    "Misc Options",
    "Misc",
    'edit_themes',
    'my-misc-options',
    'theme_admin'
);

 //etc...

A: From the codex page on admin menus:

In situations where a plugin is creating its own top-level menu, the first submenu will normally have the same link title as the top-level menu and hence the link will be duplicated. The duplicate link title can be avoided by calling the add_submenu_page function the first time with the parent_slug and menu_slug parameters being given the same value.

Personally, I think that it would be bad practice to do anything but rename the top link, as it would break consistency with the rest of the admin bar.

A: There is a workaround to hide this automatically created submenu. In the past I've used it quite often, but lately I have returned to leaving it as is (or renaming it, as m0r7if3r suggested).
Also note, that aside your main question, you have switched the positions of the menu_slug and function arguments in add_menu_page, see the codex for reference.
This is how it is done anyhow:
/* Add top level menu */
add_menu_page(
    'MyTheme',
    'MyTheme Menu Label',
    'edit_themes',
    'theme_admin',        // menu slug
    'functions.php',        // function
    get_bloginfo('template_directory') .'/img/favicon.png',
    31
);

/* remove duplicate menu hack */
add_submenu_page(
    'theme_admin',        // parent slug, same as above menu slug
    '',        // empty page title
    '',        // empty menu title
    'edit_themes',        // same capability as above
    'theme_admin',        // same menu slug as parent slug
    'functions.php',        // same function as above
}

This isn't too clean, but afaik the only way to hide the duplicate submenu.

A: There's a function that should cover this:
remove_submenu_page( $plugin_slug, $plugin_slug );


text:
Q: Angular2 loadChildren after webpacked, produces __webpack_require__ is not a function I have a simple Angular2 app using loadChildren, it works fine during development relying on SystemJs, after webpacking it, and fixing the issue with a webpack loader, the output looks like this
path: 'events', component: CoreComponents.MainLayoutComponent, loadChildren:
   function(){
      return  __webpack_require__(125)("EventModule")
   }

When I browse to /events, I get
TypeError: __webpack_require__(...) is not a function

I read through webpack repository and found this
https://github.com/webpack/webpack/issues/1890
But they say it is closed, don't know where the error is coming if it is closed, I do not use any other loaders besides the simple fix for the loadChildren syntax (similar to this https://github.com/daviddt/angular2-lazy-load-example). When I added a console log before the return statement, it retuend an "object" not a "function"
console.log(__webpack_require__(125));

returns:
1. Object
    1. EventModule:EventModule()
        1. arguments:(...)
        2. caller:(...)
        3. length:0
        4. name:"EventModule"
        5. prototype:Object
        6. __proto__:()
        7. [[FunctionLocation]]:app.js:46194
        8. [[Scopes]]:Scopes[2]
    2. __proto__:Object

What am I missing?

A: Dug deep, and finally found the answer
the line should have been using square brackets!
 return  __webpack_require__(125)["EventModule"]


text:
Q: MVC Postal conflicting with _viewstart My app is producing the error
Object reference not set to an instance of an object.
For some reason  Postal is giving an error with the layouts in the root _ViewStart.cshtml specifically the first if statement which is shown below.
_ViewStart.cshtml
    if (this.User.IsInRole("Admin") || !this.User.Identity.IsAuthenticated)
{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
else if (this.User.IsInRole("Territorial Strategic Planning Coordinator") || this.User.IsInRole("Programme Secretary") || this.User.IsInRole("IT") || !this.User.Identity.IsAuthenticated)
{
    Layout = "~/Views/Shared/_LayoutLevel1.cshtml";
}
else if (this.User.IsInRole("Divison Commander") || !this.User.Identity.IsAuthenticated)
{
    Layout = "~/Views/Shared/_LayoutLevel2.cshtml";
}
else if (this.User.IsInRole("Corps Officer") || this.User.IsInRole("Centre Admin") || !this.User.Identity.IsAuthenticated)
{
    Layout = "~/Views/Shared/_LayoutLevel3.cshtml";
}

The code I'm using within my controller is :
 dynamic email = new Email("GoalNotification");
                email.ResponseID = goal.ResponseID;
                email.User = user.UserName;
                email.To = user.Email;
                email.Send();

and the Postal View is :
GoalNotification.cshtml
To: @ViewBag.To
Subject: Goal Notification for Response : @ViewBag.ResponseID

        Dear @ViewBag.User

        This is a system generated notification to notify you that one or more of your goals need attention.

        Please revise and re-submit.

Kind Regards

TSP

    ----------------------------------------------------------------------------------

Contact Details

Office Number:

Email Address:

Physical Address:

Is there something I am doing wrong here? and is there any way to fix this?
Its my first time using Postal. Thanks for any help.
Edit: Im only getting this error because MVC Postal seems to be overriding my root _ViewStart. The program runs normal without it.
Postal has an issue when there is more than one layout specified it seems. If i have one set layout it works. Unfortunately I need to have them.
The Stack Trace :
    [NullReferenceException: Object reference not set to an instance of an object.]
   ASP._Page_Views__ViewStart_cshtml.Execute() in c:\Users\Shahil\Desktop\TSPMVC Backups\2016\28-01-2016\TSP MVC\TSP MVC\Views\_ViewStart.cshtml:3
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +73
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
   Postal.EmailViewRenderer.RenderView(IView view, ViewDataDictionary viewData, ControllerContext controllerContext, ImageEmbedder imageEmbedder) +182
   Postal.EmailViewRenderer.Render(Email email, String viewName) +204
   Postal.EmailService.CreateMailMessage(Email email) +72
   Postal.EmailService.Send(Email email) +65
   Postal.Email.Send() +56
   CallSite.Target(Closure , CallSite , Object ) +189
   System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1(CallSite site, T0 arg0) +432
   TSP_MVC.Controllers.GoalsController.AdminEdit(Goal goal) in c:\Users\Shahil\Desktop\TSPMVC Backups\2016\28-01-2016\TSP MVC\TSP MVC\Controllers\GoalsController.cs:195
   lambda_method(Closure , ControllerBase , Object[] ) +180
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
   System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9721605
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155


text:
Q: Java Regex Problem Replacing a String I am getting an exception when I try to do a replaceAll:
Symbols is a valid string.
private String buildQuery(){
        String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(**QUERY**)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

        deserializeQuotes();

        StringBuffer symbols = new StringBuffer();
        for(int i = 0; i < quotes.size();i++){
            if(i == (quotes.size()-1))
                symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote
            else
                symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C");
        }

        query.replaceAll("**QUERY**", symbols.toString());

        return query;
    }

I get the following exception:
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at android.os.Looper.loop(Looper.java:123)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at java.lang.reflect.Method.invokeNative(Native Method)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at java.lang.reflect.Method.invoke(Method.java:521)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at dalvik.system.NativeStart.main(Native Method)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104): Caused by: java.util.regex.PatternSyntaxException: Syntax error U_REGEX_RULE_SYNTAX near index 1:
08-31 10:20:58.307: ERROR/AndroidRuntime(2104): **QUERY**
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):  ^
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at com.ibm.icu4jni.regex.NativeRegEx.open(Native Method)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at java.util.regex.Pattern.compileImpl(Pattern.java:383)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at java.util.regex.Pattern.<init>(Pattern.java:341)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at java.util.regex.Pattern.compile(Pattern.java:358)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at java.lang.String.replaceAll(String.java:2004)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at org.stocktwits.activity.Main.buildQuery(Main.java:193)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at org.stocktwits.activity.Main.createDataModel(Main.java:198)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at org.stocktwits.activity.Main.onCreate(Main.java:73)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-31 10:20:58.307: ERROR/AndroidRuntime(2104):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

A: you need to escape *, because it is a quantifier
So,
query.replaceAll("\*\*QUERY\*\*", symbols.toString());


text:
Q: Read cells in csv file I have this table of numbers saved in csv file format as follow:
5,  6,  9,  5,
2,  8,  1,  1,
1,  2,  3,  6,
. . .  . .
. . .  . .
. . .  . .
. . .  . .

Every row in this table describe a rectangle dimensions.
I wanted to feed the four numbers of every row in a command line to create the rectangle as follow:
rectang -cs x1 x2  x3 x4  # rectang is a script to create rectangle; -cs flag means dimensions; x1, x2, x3 x4 the rectangle dimensions

I am thinking to convert the csv file "table.csv" to tab deliminated text "table.txt"  file then using it in a for loop as follow:
for i in $(cat table.txt); do
rectang -cs x1 x2  x3 x4
done

but I don't know how to feed x1 x2 x3 x4 from the table to the command "rectang"
Thanks for help.

A: The read command can grab multiple words, separated by characters in $IFS (default: space, tab, newline)
while read -r d1 d2 d3 d4; do
    rectang -cs "$d1" "$d2" "$d3" "$d4"
done < file.csv

Given your modified data (fields separated with comma and spaces), I'd do this:
while IFS=",$IFS" read -r d1 d2 d3 d4; do # ...

to include the comma as a field separator.

A: If the file is like that:
cat table.txt | while read i
do
    rectang -cs  $i
done

This will call:
rectang -cs 5  6  9  5
rectang -cs 2  8  1  1

etc.

A: The answer by Glenn is of course mighty fine, but in this type of cases I would use awk to generate the command lines, and then pipe the results to a shell. As awk is part of POSIX, it arguably would be a valid solution.
awk -F'[, ]+' '{print "rectang -cs", $1, $2, $3, $4}' table.csv | sh

or, assigning the first field to the first field to trigger a recomputation of the field separator:
awk -F'[, ]+' '$1=$1{print "rectang -cs", $0}' table.csv | sh

Alternatively, with a similar pattern:
sed -e 's/^/rectang -cs /' -e 's/, */ /g' table.csv | sh

Of course, while experimenting, you can just look at the commands, and only if you are really sure, you pipe it to sh.


text:
Q: Is there a library that can extract personal informations out of text? I am looking for a library that when given text like this :
"I don't know, this wasn't the first time. But as I said I'm 45yo male now and I'd rather not do things like that again"
Will return some object containing informations like this : {"gender":"male", "age":45}
(Ideally something evolved enough that it recognizes different ways of saying it, ex: "I'm 45" / "Im 45" / "I am now 45yo",  "I turned 45 yesterday" etc

A: Within NLP, the task you're looking for is identifying/detecting PII (personally identifiable information). Depending on your budget/scope, AWS offers PII detection within Amazon Comprehend.
Alternatively, pii-codex offers an open source solution that may meet your needs.


text:
Q: Cordova media plugin - stop streaming not working - release() freezes the device I am using cordova 6.4.0 with cordova-plugin-media for streaming radio-stations in an Android Application. Unfortunately there is a case, where the application is not responding properly anymore.
Let's say the user wants to stream a radiostation, but while the stream is loading, he wants to abort it (for example because the stream is down, or taking very long to load).
In this case I am not able to cancel the process!
media = new Media("http://direct.franceinfo.fr/live/franceinfo-midfi.mp3?ID=f9fbk29m84", mediaPlayerSuccess, mediaPlayerFail, mediaPlayerStatus);
media.play();

Now I want to cancel the process of buffering the stream, but I'm not able to. The functions:
media.pause();
media.stop();

are throwing error messages in the ADB-log and are calling the mediaPlayer-onError callback.
D/AudioPlayer( 3362): AudioPlayer Error: pausePlaying() called during invalid state: 1
...
D/AudioPlayer( 3362): AudioPlayer Error: stopPlaying() called during invalid state: 1

The media.release() command stops the loading of the stream! However just releasing the stream without stopping it, causes other, rather big problems:
Most of the times the system reacts just very slow and hangs a few seconds, if you call media.release() on a media-object. But if you do this often, the system completly freezes. Meaning it does not accetp remote-control commands anymore.
The Adb-log is still working, but does not show any errors in this case. Only the POWER-Button is still working (it locks and unlocks the screen). The only way to recover from this screwed-up state, is to reboot the device.
How am I supposed to cancel a Media-stream if it is not playing, yet? Is this a bug in the plugin?
Attached is the code-snippet, that I use to handle the media-streaming-logic. Like described above... it basically works, but it slows down or even freezes device, if you call it multiple times.
function radioControl(action, media_src){
  //media_src is a webradio-streamurl.

  if(action == 'play') {

    // Initial Play
    if(media === null){
      mediaCreateObject(media_src);
    }

    // If we get PLAY but on antoher station
    else if(media.src != media_src){
      mediaReleaseRessources();
      mediaCreateObject(media_src);
    }

    //interrupt_timer = false;
    if(media === null){
      mediaCreateObject(media_src);
    }
    media.play();
  }
  else if (action === 'pause') {
    //If we get "pause", but it didn't even start yet
    if(media._duration == -1){
      mediaReleaseRessources();
    }
    else{
      media.pause();
    }
  }
}

function mediaCreateObject(media_src){
  media = new Media(media_src, mediaPlayerSuccess, mediaPlayerFail, mediaPlayerStatus);
}

function mediaReleaseRessources(){
  media.release();
}

A: I found out, that this is not a cordova issue, but an 8 year-old (!) android-bug, that was never fixed. See here:
https://code.google.com/p/android/issues/detail?id=959

MediaPlayer "crash" (deadlocks the calling thread) when resetting or releasing an unused MediaPlayer

Basically the problem is: If you try to "release" a media-object that is not playing (yet), it will deadlock the calling thread, which causes the freezing that I have mentioned in the question. Unfortunately they never fixed this bug, but just marked it as "obsolete". In Android 5.1.1. the bug apparently is still there. Maybe they fixed it in later versions.

I have made a rather ugly workaround for this problem, but it is working. Basically what I did is:
We save every media-object in a javaScript-object. If the user stops it, while it plays, we can just stop and delete the object. But if it is not playing, we leave this media-object in this javaScript-object media_objects = {};
Also we save the currently active_media stream in a variable.
If cordova calls the mediaPlayerStatusChange-callback we loop through the media_objects and check if the status of one of the "pending"-objects has  now changed to "running". - Cordova justs calls the media-status-change-callback without any indictation what media-object exactly just changed the state. That is unfortunate, so we have to check if one of the pending-"obsolete" objects now started playing. If so, we can stop and release it. (If the object is actually playing, stop and release works like intended - only if it's not playing, it causes the crash)
function mediaPlayerStatusChange(status){
  mediaReleaseRessources();
  // handle status change....
  // ......
}

function mediaReleaseRessources(){

  for(var key in media_objects) {
    // We can only stop-and release an object, if it is playing
    // If an object started playing, the "_duration"-value is != -1
    if(key !== active_media && media_objects[key]._duration != -1) {
      media_objects[key].stop();
      media_objects[key].release();
      delete media_objects[key];
    }
  }
}

This solution works for me, however I am still interested in a better and cleaner way to handle multiple media-streams in cordova.


text:
Q: bitnami/WordPress chart - embed uploads in a custom image I am using bitnami/WordPress chart https://github.com/bitnami/charts/tree/master/bitnami/wordpress/
I am looking for a way to use a custom image which embed a specific wp app state (plugins + themes + uploads) ... I know that for themes and plugins can be use a script to do that ... but I want to embed it all
I tried this:

*

*starting from https://github.com/bitnami/bitnami-docker-wordpress.git

*using docker-compose I installed locally wp using volumes

*all the generated wp content I copied it to rootfs folder then build and tag my custom image, then docker push to my repo

*updated values.yaml to use my custom image

After helm install and wait for WordPress pod to be ready ... the pod does not contain the uploads files

A: You can replace image using custom values.yaml file.
For example you can create values.yaml containg this content
image:
  registry: "docker.tools.private.services"
  tag: 5.6.0-debian-10-r23

Documentation for all values, you can find in the README.md for that chart.
This docs are generated directly from values.yaml file, so you can use directly the values.yaml file
Then install it with helm:
helm install my-release bitnami/wordpress -f ./values.yaml

Volume override
In the bitnami chart there is volume mount under the /bitnami/wordpres. Make sure it does not cover your image file system.
For example for me it is mount like this:
kubectl describe pod blog-wordpress-5698fc9584-jklhl

    Mounts:
      /bitnami/wordpress from wordpress-data (rw,path="wordpress")
...
...
...

Volumes:
  wordpress-data:
    Type:       PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)
    ClaimName:  slide-blog-wordpress
    ReadOnly:   false


text:
Q: British slang: larl I've seen this word a couple of times in twitter and I've not gotten a clear definition. A friend of mine wrote a mock British text that went like this "al av ya mum ya larl cunt" so that might give context.

A: For the sake of completeness:

al av ya mum ya larl cunt

al = I will -> I'll -> ah'll
av = have -> 'ave (in this case have has overtly sexual connotations as in "have sexual relations with")
ya = your -> ya'r -> ya
mum = mother (not really slang)
ya = you -> ya
larl = little -> lirle -> lahrl
And the last word is so commonly used I feel I need not explain it :)
As I said in the comment, but also for future reference: do not use sentences like this unless you are in really intimate company. Not all strangers are likely to react well to statements of this kind :)


text:
Q: Finding the minima and the transition state in a potential energy surface (PES) Problem Background:
I am trying to simulate a potential energy surface (PES) which represents the different states that a triatomic molecule (A-B-C) can have in 3D and its corresponding ContourPlot.
The potential function, depending on the distance between atom A and atom B (which I called r) and the distance between atom B an atom C (which I called d) has the following form (which I arbitrarily chose):
crazypotential =  1/r^12 - 2/r^6 + 1/d^12 - 2/d^6 -
(2 Exp[-(r - d)] + 2Exp[-(d - r)] -  2 Exp[-(2 (r - d) - (d - r))*Cos[d]]);

Plot3D[crazypotential, {r, .8, 1.6}, {d, .8, 1.6}]

Show[ContourPlot[crazypotential, {r, 0.75, 2}, {d, 0.75, 2}, PlotLegends -> Automatic,
                 Contours -> 15, ContourStyle -> Directive[Black, Opacity[.3]],
                 ColorFunction -> "LakeColors"],
     Graphics[Text["Transition State", {1.1, 1.3}]]]

As you can see, there are clearly two minima and one transition state. Now, my question is the following:
I want to know exactly where the minima (deep blue) and the transition state are. For that I do something like:
Solve[D[crazypotential, {r, d}] == 0 && r < 1.6 && d < 1.6, {r, d}, Reals]

But does not seem to work. Do you have any ideas about how I could try to solve these minima and transition state in this region (both r and d going from 0.8 to 1.6)? Or do you see any mistake in my code that could be the reason why it is not working?
Thank you very much in advance!

A: As you know, what you call "transition state" is in particular a critical point of crazypotential, i.e., a point where both partial derivative of crazypotential with respect to r and d vanish. A "root" of the derivative of crazypotential so to say.
You already read off a good guess for the transition state. You can refine that with Newton's method which is effectively performed by FindRoot.
Dcrazypotential = D[crazypotential, {{r, d}, 1}];
FindRoot[Dcrazypotential == {0, 0}, Transpose@{{r, d}, {1.1, 1.3}}]

{r -> 1.01146, d -> 1.31042}

The same is also applicable to the minimizers; they are also roots of Dcrazypotential -- if they exist. I have to say that crayzpotential is not bounded from below on $\mathbb{R}^2$, so there are no global minimizers. Still, there might exist local minimizers...
If you want to constrain r and d to lie between 0.8 and 1.8, then minimimal values are attained at the box boundary. The can be detected with
FindRoot[Dcrazypotential[[1]] == 0 /. d -> 1.8, {r, 1.}]
FindRoot[Dcrazypotential[[2]] == 0 /. r -> 1.8, {d, 1.}]

A: Adapting the approach from this answer, here is how to use the MeshFunctions option of ContourPlot[] to find critical points:
potential[r_, d_] := 1/r^12 - 2/r^6 + 1/d^12 - 2/d^6 -
         (2 Exp[-(r - d)] + 2 Exp[-(d - r)] - 2 Exp[-(2 (r - d) - (d - r)) Cos[d]])

(* gradient and Hessian *)
{dr[r_, d_], dd[r_, d_]} = D[potential[r, d], {{r, d}}];
hes[r_, d_] = D[potential[r, d], {{r, d}, 2}];

crit = Cases[Normal[ContourPlot[dr[r, d] == 0, {r, 3/4, 2}, {d, 3/4, 2},
                                ContourStyle -> None, Mesh -> {{0}},
                                MeshFunctions -> Function[{r, d, f}, dd[r, d]]]],
             Point[{r0_, d0_}] :> ({\[FormalR], \[FormalD]} /.
                                   FindRoot[{dr[\[FormalR], \[FormalD]],
                                             dd[\[FormalR], \[FormalD]]},
                                            {{\[FormalR], r0}, {\[FormalD], d0}}]), ∞]
   {{1.01146, 1.31042}}

where we see that only one critical point is returned. Let's test it:
hc = hes @@ crit[[1]];
Through[{PositiveDefiniteMatrixQ, IndefiniteMatrixQ, NegativeDefiniteMatrixQ}[hc]]
   {False, True, False}

This verifies that the point we found is a saddle point.


text:
Q: Android Dev: High noise floor on audio recordings on Samsung Galaxy S6 I am building an app to analyze voice quality.The user makes a voice recording which is stored on the device and then sent to a server for analysis.
I recently noticed that all audio recordings from Samsung Galaxy S6 (G920-F) are much noisier than other tested Android devices. I need to support the Galaxy S6 as I have many users on this phone.
I an attempt to fix the issue I tried testing MediaRecorder with different Audiosources such as: DEFAULT, MIC, VOICE_RECOGNITION and VOICE_COMMUNICATION. None of these options have a significant impact on noise.
I then tested using AudioRecorder with the same AudioSources listed above. No improvement.
Finally I tried adding a NoiseSuppressor to AudioRecorder which showed very little to no improvement.
I am setting up the AudioRecorder and NoiseSuppressor as follows:
public void startRecording(String fileNameIn) {
        bufferSize = AudioRecord.getMinBufferSize (
                RECORDER_SAMPLERATE,
                RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING);
        aRecorder = new AudioRecord(
                MediaRecorder.AudioSource.VOICE_RECOGNITION,
                RECORDER_SAMPLERATE,
                RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING,
                bufferSize);

        int audioSession = aRecorder.getAudioSessionId();
        enableNoiseSuppressor(audioSession);

        aRecorder.startRecording();
        ......

and
public void enableNoiseSuppressor(int microphoneId) {
        if (NoiseSuppressor.isAvailable() && noiseSuppressor == null) {
            noiseSuppressor = NoiseSuppressor.create(microphoneId);
            noiseSuppressor.setEnabled(true);
            Log.i(TAG, "NoiseSuppressor enabled");
        } else {
            Log.e(TAG, "This device don't support NoiseSuppressor");
        }
    }

I also tested 3rd party recording apps on the Galaxy S6 and notice a high noise level on these recordings as well. This seems like a strange problem to have from a flagship (a few years back) phone. Are there any Android tricks or core concepts I am missing?
Looking for any suggestions or advice.


text:
Q: Filebeat unable to access logs under "/var/lib/docker/containers" path due to Permission Denied issue I am trying to deploy ELK stack with Filebeat in Openshift environment.
Filebeat is trying to read the log files under "/var/lib/docker/containers" path of a pod but it failed with "Permission Denied" error.
I am using an SCC with "runsAsAny" and "runAsUser: 0",
- apiVersion: v1
  kind: SecurityContextConstraints
  metadata:
    name: hostpath
  allowPrivilegedContainer: true
  allowHostDirVolumePlugin: true
  runAsUser:
    type: RunAsAny
  seLinuxContext:
    type: RunAsAny
  fsGroup:
    type: RunAsAny
  readOnlyRootFilesystem: false
  supplementalGroups:
    type: RunAsAny
  users:
  - my-admin-user
  groups:
  - my-admin-group

Volume Mounts:
volumeMounts:
- mountPath: /var/lib/docker/containers
  name: varlibdockercontainers

HostPath Volume:
securityContext:
  runAsUser: 0
volumes:
- hostPath:
    path: /var/lib/docker/containers
    type: ""
  name: varlibdockercontainers

Please let me know if I am missing something in SCC to have atleast read permissions in "/var/lib/docker/containers" path.


text:
Q: Female OBD2 Connector Does anyone know what's this exact connector:

I got it from here, but I lost these metal connectors, and I was hoping to find them at DigiKey or similar sites, but the one that I was able to find is for slightly different connector, female obd2 connector which you can find there which looks like this, and that one does not fit into the socket that I have from AliExpress (which I need):


text:
Q: How to Avoid Non-Related Views from Rendering on State Variable Updates I have created two triangle shapes and I am trying to color each of them individually when I click on it. The @State variable is created inside PaintView which creates a Shape that contains a single path.

The behavior I'm seeing is that whenever I click on a shape, it re-creates both shapes, instead of only the one I'm tapping on (I can observe this based on the print that I've added to BuildShape).
Now, my understanding is that whenever a state changes, SwiftUI will re-render the entire View that contains that @State, and its child views, but since my shapes are in different views that don't relate, why is SwiftUI re-rendering both of them?
This diagram shows how the views related to each other:

For example, this is what happens when I tap on the bottom triangle:

*

*When I tap on the bottom triangle for the first time, SwiftUI re-creates the bottom triangle twice, and the top triangle once

Path: 0 0 m 100 100 l 200 0 l
Path: 100 100 m 0 200 l 200 200 l
Path: 100 100 m 0 200 l 200 200 l

*When I tap on the bottom triangle again (and for as many other times), SwiftUI re-creates the bottom triangle once, and the top triangle once

Path: 0 0 m 100 100 l 200 0 l
Path: 100 100 m 0 200 l 200 200 l

This is the code I'm using:
import SwiftUI
import UIKit

struct BuildShape: Shape {
    let path: Path

    func path(in rect: CGRect) -> Path {
        print("Path:", path)
        return path
    }
}

struct PaintView: View {
    let path: Path
    @State var color = Color.black

    var body: some View {
        BuildShape(path: path)
            .fill(self.color)
            .onTapGesture(count: 1) {
                self.color = Color.blue
        }
    }
}

struct DrawView: View {
    var triangle1Path: Path {
        var path = Path()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: 100, y: 100))
        path.addLine(to: CGPoint(x: 200, y: 0))
        return path
    }
    var triangle2Path: Path {
        var path = Path()
        path.move(to: CGPoint(x: 100, y: 100))
        path.addLine(to: CGPoint(x: 0, y: 200))
        path.addLine(to: CGPoint(x: 200, y: 200))
        return path
    }

    var body: some View {
        ZStack {
            PaintView(path: triangle1Path)
            PaintView(path: triangle2Path)
        }
    }
}

A: The views containing triangle shapes are overlap (because they are in ZStack), and as views by default are not opaque, changing one can affects resulting appearance so redrawn all in ZStack.
ZStack {
    PaintView(path: triangle1Path)
    PaintView(path: triangle2Path)
}

Put them for example into VStack and you'll see that only tapped is redrawn, because rendering engine knows now that views independent.
VStack {
    PaintView(path: triangle1Path)
    PaintView(path: triangle2Path)
}


text:
Q: Getting callback from widgets instantiated with for-loop - Flutter Background: I am instantiating a series of card items in a stateful widget tree using for (var card in menuLists[_selectedIndex]) card This is creating a series of card widgets that I can scroll through. Each of the cards also has an add-to-cart button that navigates to a new page where a user will click a subsequent add-to-cart button that should then increment a counter Text() widget on the page where the cards are first instantiated, as well as do a few other things cart related.
Counter Text() Widget:
int numberOfItemsInCart;

Text(
     numberOfItemsInCart.toString(),
     style: GoogleFonts.ubuntuMono(fontSize: 23),
),

In the first button, there is an onPressed() as shown below that awaits a callback variable from a Navigator.onPop(context, 'variable') that is triggered on the second page by the second add-to-cart button being clicked.
First add-to-cart button:
bool doAddItemToCart = false;

MaterialButton(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(32),
                              ),
                              child: Text(
                                'Add to Cart',
                                style: GoogleFonts.ubuntuCondensed(
                                  fontSize: 17,
                                  color: colorPalette.chooseColor('white'),
                                ),
                              ),
                              color: colorPalette.chooseColor('lightGreen'),
                              onPressed: () async {
                                doAddItemToCart = await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => AddToCart(
                                        menuItemName, menuItemOptions),
                                  ),
                                );
                              },
                            ),

Second add-to-cart button:
Expanded(
              flex: 1,
              child: Wrap(
                children: [
                  Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(bottom: 8),
                    child: MaterialButton(
                      minWidth: 296,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(32),
                      ),
                      color: colorPalette.chooseColor('darkGrey'),
                      onPressed: () {
                        setState(() {

                        });
                        Navigator.pop(context, /*boolValue*/);
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            backgroundColor:
                                colorPalette.chooseColor('offWhite'),
                            duration: Duration(seconds: 1),
                            content: Text(
                              'Item added to cart',
                              style: GoogleFonts.ubuntu(
                                color: colorPalette.chooseColor('darkGrey'),
                              ),
                            ),
                          ),
                        );
                      },
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          'Add to Cart!',
                          style: GoogleFonts.ubuntuCondensed(
                            fontSize: 23,
                            color: colorPalette.chooseColor('white'),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),

Essentially, I need to communicate the doAddItemToCart boolean value to the stateful widget, which contains the list of card widgets, that, based on its value, will increment the counter or not.
Problem: The problem is that I don't know how to get the values returned to the individual cards from the second add-to-cart button's Navigator.pop() and subsequently increment the counter Text() widget. I considered using global variables but that is kind of frowned upon. I also considered using an inherited widget, but I don't this I need to go there. I am new to Flutter and Dart btw so please have mercy. Does anyone know an easy workaround for this? Please let me know if I should provide more clarification.

A: The problem is that I don't know how to get the values returned to the individual cards from the second add-to-cart button's Navigator.pop() and subsequently increment the counter Text() widget.
Instead of sending an item name and option, you can send your Item object to add cart.
So, instead of this:
doAddItemToCart = await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => AddToCart(
                                        menuItemName, menuItemOptions),
                                  ),
                                );

change to:
selectedItem = await Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => AddToCart(
                                        item, menuItemOptions),
                                  ),
                                );

where item, is your object item.
then, when you adding the item to the cart, include it when popping:
Navigator.pop(context, item);

Now, you can check if the navigator returning a selected item or not:
selectedItem = await Navigator.push(...);
if(selectedItem != null & selectedItem is YourItemObject) {
    // Add to cart.
}


text:
Q: Inner Join de Consultas Les comento, yo tengo una query que tiene una consulta que me trae determinados idusuarios sometidos a determinadas condiciones, y tengo otra consulta con otros idusuarios sometidos a otras condiciones, por lo que tendría
CONSULTA 1: XXX idusuarios
CONSULTA 2: XXX idusuarios

Mi pregunta es: ¿Hay alguna manera de hacer un INNER JOIN de esas consultas, trayendo solamente donde coinciden los idusuarios ?

A: tal vez puede ayudarte algo como esto:
select
    *
from
    schema.table1 a
    inner join schema.table2 b on (a.id_usuario=b.id_usuario)


text:
Q: How to correct already "added to index" files in git? My question is how to correct files which I already added to index:

*

*git init

*git add index.html

Let's say I want to commit some changes in my index.html. How to do that?

A: The index does not just list files, it actually contains copies of files.  This thing—this index, or staging area, or cache—holds a copy of every file, except for any files you specifically want to be missing in the commit.  The thing is so important that it has these three names.  (Or, perhaps, the first name used for it was so bad that it grew a couple of extra names.  Either way it now has these three names.)
Git stores commits as snapshots.  Each commit has a copy of all of your files—all of the files that were in the index, that is, at the time you ran git commit.  They're stored in a special, frozen/read-only, compressed, Git-only format.  That's fine for archives, but useless for getting work done.  Remember that for the next few bits.
When you tell Git git checkout master, you're telling Git: Find the commit identified by the name master.  Copy those files into your index, then copy them from your index to my work-tree so that I can see the files and work on them.  In your work-tree, the files are normal.  You can use them.  Your computer can use them.  You can change them, rename them, remove them, whatever you want.
When you tell Git git add somefile, you're telling Git: Copy the file somefile from my work-tree, where I can see it and work on it, into your index so that it's ready to go into the next commit.  The copy that's in the index is in the special Git-only format, but—until you commit it anyway—it's not frozen.  It's just ready to freeze.
When you tell Git git rm somefile, you're telling Git: Remove the file somefile from my index and from my work-tree.  If you use --cached, as in git rm --cached somefile, you tell Git to remove it from the index, but leave it alone in the work-tree.
When you tell Git git commit, you're telling Git: Take all the files that are in the index right now.  Freeze them into a new commit.  Whatever is in the index then, that's what's in your new commit.  Whatever isn't in the index, that's not in your new commit.  So your new commit is a snapshot.  The index contains the proposed next snapshot.  You can change it around as much as you like, at any time: git add copies files into it, replacing the old one or making a new one depending on whether there was one of that name in there before.  Arrange—or "stage", hence the name "staging area"—the files as you like, then use git commit to freeze them into a snapshot.


text:
Q: Split string with specified separator without omitting empty elements Right now I am using
StringUtils.split(String str, char separatorChar)

to split input string with specified separator (,).
Example input data:
a,f,h

Output
String[] { "a", "f", "h" }

But with following input:
a,,h

It returns just
String[] { "a", "h" }

What I need is just empty string object:
String[] { "a", "", "h" }

How can I achieve this?

A: You can just use the String.split(..) method, no need for StringUtils:
"a,,h".split(","); // gives ["a", "", "h"]

A: You could use this overloaded split()
public String[] split(String regex,
                  int limit)

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter
For more visit split

A: The ordinary String.split does what you're after.
"a,,h".split(",")  yields  { "a", "", "h" }.
ideone.com demonstration.

A: If you are going to use StringUtils  then call the splitByWholeSeparatorPreserveAllTokens() method instead of split().

A: Split string with specified separator without omitting empty elements.
Use the method org.apache.commons.lang.StringUtils.splitByWholeSeparatorPreserveAllTokens()
Advantage over other method's of different class :

*

*It does not skip any sub-string or empty string and works fine for all char's or string as delimiter.

*It also has a polymorphic form where we can specify the max number of tokens expected from a given string.

String.Split() method take's regex as parameter, So it would work for some character's as delimiter but not all eg: pipe(|),etc. We have to append escape char to pipe(|) so that it should work fine.
Tokenizer(String or stream) - it skips the empty string between the delimiter's.


text:
Q: Gradle >=4.6: using java-library & java plugins simultaneously in multi-module build Since Gradle 4.6:

*

*https://docs.gradle.org/4.6/userguide/java_library_plugin.html#sec:java_library_separation

*https://docs.gradle.org/4.6/release-notes.html#compile/runtime-scope-separation-in-pom-consumption
new configurations were added: api (only in java-library plugin) & implementation (defined by both).
In multi-module project I have several "core" modules that act as internal libraries and sometimes need to pass exposed compile time dependencies via api configuration.
Previously we applied java plugin recursively:
subprojects {
    apply plugin: 'java'
}

To be purist we can apply java-library plugin to "library" modules  and java plugin to "end-application" modules.
What if we just put:
subprojects {
    apply plugin: 'java'
    apply plugin: 'java-library'
}

NOTE With proper naming schema (we don't have one) it is possible to do selectively:
subprojects {
    if (project.name.startsWith('lib-')) {
        apply plugin: 'java-library'
    } else {
        apply plugin: 'java'
    }
}

A: The java-library plugin "expands" the base java plugin, so you can simply apply java-library plugin to all your sub-projects, this will automatically apply java plugin.
As you mentioned, the ideal/purist way would be to apply java-library plugin only on "library" projects, but you can still apply this plugin to "end application" modules and this will work (of course in such modules you would use implementation configuration and not api as it would not make sense).
Another approach would be to apply the needed plugin directly in sub-projects build script and not globally from the root project build; you would not need to define a "naming schema" in this case.


text:
Q: How to determine, if an Angular Component is opened as dialog? I want to implement an Angular component, which can be opened both as a MatDialog, or displayed normally.
If it's opened as a dialog, I want to display a close button for the user, to be able to close the dialog. To implement this, I have to inject the MatDialogRef service into the component.(If I try to inject it in all of the 2 scenarios and the component is opened via the router, it throws an error.)
I found a solution where I inject the MatDialogRef service conditionally. In this solution I have to use an Input parameter, which determines if the Component is opened as a dialog.
My question is the following:
Is there another way for the component, to determine if it is opened as a dialog, so the input parameter is not nessecary anymore, and the component is more self contained?
My code:
The parent component opening the dialog:
openCutDataViewer(cutterPackageNumber: number) {
    let tempCutterPackageNumber = 12312432423;
    const dialogRef = this.dialog.open(CutterPackageDetailsComponent, {
      width: '95vw',
      maxWidth: '95vw !important',
      height: '95vh',
    });
dialogRef.componentInstance.openedAsDialog = true;
    dialogRef.componentInstance.cutterPackageNumber = tempCutterPackageNumber;

  }

The dialog/normal component:
import { Component, Injector, Input, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { InsulationCheckService } from '../insulation-check.service';
import { CutterPackage } from '../models/cutter-package.model';

@Component({
  selector: 'app-cutter-package-details',
  templateUrl: './cutter-package-details.component.html',
  styleUrls: ['./cutter-package-details.component.scss'],
})
export class CutterPackageDetailsComponent implements OnInit {
  @Input() cutterPackageNumber?: number;
  @Input() openedAsDialog: boolean = false;

  dialogRef?: MatDialogRef<CutterPackageDetailsComponent>;
  data?: CutterPackage;

  constructor(
    private insulationCheckService: InsulationCheckService,
    private injector: Injector
  ) {}

  ngOnInit(): void {
    //if insulation packageNumer is provided as input
    if (this.cutterPackageNumber) {
      this.insulationCheckService
        .getCutterPackageData(this.cutterPackageNumber)
        .subscribe((cutterPackage) => (this.data = cutterPackage));
    }

    //if opened as dialog, inject dialog service
    if (this.openedAsDialog) {
      this.dialogRef = <MatDialogRef<CutterPackageDetailsComponent>>(
        this.injector.get(MatDialogRef)
      );
    }
  }

  closeDialog() {
    if (this.dialogRef) {
      this.dialogRef.close();
    }
  }
}


text:
Q: Automating WSDL.exe in a Custom Build I have a web application written in C# that consumes several internal web services.  We have a development tier, a testing tier, and a production tier.  Also, we use the WSDL.exe command to generate a Proxies.cs file for a given tier's web services.
When we are ready to deploy our code up the stack from development to test or test to production, we need to run the WSDL.exe command to point to the appropriate version of the web services.
Is there a generally accepted way to automate this?

A: There are a number of way to do it.  A NAnt build script will do it, but I think the most commonly accepted method now is to use MSBuild.  See MSDN for details.

A: Our company uses a combination of NANT + Cruise Control + Custom Utility apps to build our products.  More specifically, the  task in NANT will allow you to fire off those command-line applications such as WSDL.exe


text:
Q: SensorGesture from qml plugin not working I am following this tutorial to detect shaking of the phone. This is a part of iOS app development.
import QtQuick 2.0
import QtQuick.Layouts 1.1
import QtMultimedia 5.0
import QtGraphicalEffects 1.0
import QtSensors 5.0 as Sensors

SceneBase {
    id: screen

///*** Code of Interest ***///

    Sensors.SensorGesture {
        id: sensorGesture
        enabled: true
        gestures : ["QtSensors.shake"]

        onDetected: {
          console.log("phone shake detected")
        }
    }

/// ************************* ///

    Sensors.Gyroscope {
        id: gyro
        dataRate: 10
        active: true

        onReadingChanged: {
            if (reading.y > 1100){
                console.log("rapid motion detected")
            }
        }
    }

    //... bunch of other code
}

All other Sensors work fine when code pertaining to Sensors.SensorGesture is commented out. However, it gives the following error when the code is uncommented.
Could not load  QtQuick2Plugin(0x146a5b80)
Could not load  QtQuick2WindowPlugin(0x146a7df0)
Could not load  QMultimediaDeclarativeModule(0x146a4020)
Could not load  QtQuickLayoutsPlugin(0x146a8120)
Could not load  QtSensorsDeclarativeModule(0x146aa6d0)
Could not load  QtQuickControlsPlugin(0x146aa870)
Could not load  QQmlLocalStoragePlugin(0x146aa9c0)
Could not load  QtQuick2ParticlesPlugin(0x146aa9e0)
Could not load  AVFServicePlugin(0x146aabf0)
Could not load  AVFMediaPlayerServicePlugin(0x146aac20)
Could not load  AudioCaptureServicePlugin(0x145a83e0)
Could not load  CoreAudioPlugin(0x145a9410)
Could not load  QM3uPlaylistPlugin(0x145a7ff0)

Could not load  QDDSPlugin(0x145a8ae0)
Could not load  QICNSPlugin(0x145a92c0)
Could not load  QICOPlugin(0x145a8760)
Could not load  QJp2Plugin(0x145a8a50)
Could not load  QMngPlugin(0x145a8e60)
Could not load  QTgaPlugin(0x145a8f30)
Could not load  QTiffPlugin(0x145a8fb0)
Could not load  QWbmpPlugin(0x145a9320)
Could not load  genericSensorPlugin(0x145a8da0)
Could not load  IOSSensorPlugin(0x145a8e30)
Could not load  QtQuick2Plugin(0x146a5b80)
Could not load  QTcpServerConnection(0x145a82e0)
Could not load  QGenericEnginePlugin(0x145a87f0)
Could not load  QSQLiteDriverPlugin(0x145a8970)
Could not load  QIOSIntegrationPlugin(0x14539070)

Please help me.

A: As of 5.13, sensor gestures are not supported in Qt for iOS
See the compatibility map: https://doc.qt.io/qt-5/compatmap.html
I managed to work around it with this extension, linked to the Qt app in a .mm file:

#import "UIKit/UIKit.h"

@implementation UIWindow (WoboqWindow)

extern void sendShakeDetectedToRootObject();
- (void)motionEnded:(UIEventSubtype)motion
  withEvent:(UIEvent *)event {
    NSLog(@"motionEnded %@", event);

    if (motion == UIEventSubtypeMotionShake )
    {
        NSLog(@"Shake it!");
        sendShakeDetctedToRootObject();
    }
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"motionBegan %@", event);
}

@end

With this main main.cpp:

void sendShakeDetectedToRootObject() {
    QMetaObject::invokeMethod(rootObject, "shakeDetected");
}

The rootObject you get from the QML engine.


text:
Q: Matching pairs and triplet substrings from a string I have a system where a string will be received from the user. I have a list of words which basically classifies what category that word belongs to. This will look something like this:
classifier = {"delhi":"place",
"new-delhi":"place",
"java":"skill",
"python":"skill"}

Suppose the query comes out to be java jobs in new delhi. What I have thought of implementing is given below:

*

*Slugify the string

*Pick triplets from string like (0,1,2),(1,2,3) and so on.

*If a triplet is mapped into the classifier dict,pop it from the string,store it and continue with the processing.

Similarly the task will be repeated for pairs and singles.
The above method will give me complexity of around 3n where n is the length of the string.
Is there any other/better way of doing this?


text:
Q: Akka-HTTP JSON serialization How does one control the deserialization for spray-json? For example, I have a class defined as:
case class A (Name:String, Value:String)
And I would like to deserialize the following JSON into a List of A objects:
{
   "one": "1",
   "two": "2"
}

and it should become:
List(A("one", "1"), A("two", "2"))

The problem is that the default JSON representation of that List is this one, which I do not want:
[
   { "Name": "one", "Value": "1" },
   { "Name": "two", "Value": "2" }
]

How can I accomplish this?

A: You can write your own custom deserializer for the structure you are looking for:
  case class A(Name:String, Value:String)

  implicit object ListAFormat extends RootJsonReader[List[A]] {
    override def read(json: JsValue): List[A] = {
      json.asJsObject.fields.toList.collect {
        case (k, JsString(v)) => A(k, v)
      }
    }
  }

  import spray.json._

  def main(args: Array[String]): Unit = {
    val json =
      """
        |{
        |   "one": "1",
        |   "two": "2"
        |}
      """.stripMargin

    val result = json.parseJson.convertTo[List[A]]
    println(result)
  }

Prints:
List(A(one,1), A(two,2))


text:
Q: link html button to java activity I'm making an Android app to my book I have an html page I want to add a button on it which is linked to this Java code
public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // listeners of our two buttons
    View.OnClickListener handler = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {

                case R.id.buttonShareTextUrl:
                    shareTextUrl();
                    break;

            }
        }
    };

    // our buttons
    findViewById(R.id.buttonShareTextUrl).setOnClickListener(handler);

}

// Method to share either text or URL.
private void shareTextUrl() {
    Intent share = new Intent(android.content.Intent.ACTION_SEND);
    share.setType("text/plain");
    share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);

    // Add data to the intent, the receiving app will decide
    // what to do with it.
    share.putExtra(Intent.EXTRA_SUBJECT, "book");
    share.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.sohaibm.assrar_bac");

    startActivity(Intent.createChooser(share, "share with"));
}

}
so I want you to give me an HTML code of the page that contains the button linked to this activity and thank you so much

A: If you use WebView to show book content you can use WebViewClient:
WebViewClient mWebClient = new WebViewClient(){

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(url.startsWith("handle:")){
                // do something
                return true;
            }

            else{
                view.loadUrl(url);
            }
            return true;
        }
    };
    mWebView.setWebViewClient(mWebClient);

And your link should be:
Link text

A: Try like this:
Html Page:

        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="style.css" />

            <input type="button" value="Locate" onClick="moveToScreenTwo()" />

FirstACtivity.java:
import android.webkit.JavascriptInterface;

webView = (WebView) findViewById(R.id.load_url);
webView.getSettings().setJavaScriptEnabled(true);

 if (new File(url).exists()) {
            webView.loadUrl(FILENAME_PREFIX + url);
            Log.d("fileurl", "" + FILENAME_PREFIX + url);
  webView.addJavascriptInterface(new WebAppInterface(this), "Android");
        }
  //Class to be injected in Web page
    public class WebAppInterface {
        Context mContext;

        /**
         * Instantiate the interface and set the context
         */
        WebAppInterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void moveToNextScreen() {

            Intent i = new Intent(FirstActivity.this,SecondActivity.class);
            startActivity(i);

        }
     }

For more Reference: Check this tutorial.


text:
Q: Why does parseInt warn of using valueOf When looking at the source code for Integer.parseInt(String s, int radix) (java 8, 1.8.0_131), I found the following comment block:
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/

While I understand the first part about the IntegerCache, I don't understand why there's a warning about valueOf, and why in this context.
I see that valueOf() relies on parseInt(), but I still don't get why there's this warning.
Can someone explain what exactly the comment warns me about (and the context where valueOf shouldn't be used), and what could possibly go wrong.
Edit:
The code in Integer.valueOf(int i) seems to have changed since the other question from the comment below was asked, it is now
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

and should be save from the assertion error before.

A:
Can someone explain what exactly the comment warns me about (and the context where valueOf shouldn't be used), and what could possibly go wrong.

The Integer class creates and maintains a cache of Integer objects representing small integer values; by default, values in the range -128 to 127 are covered (more discussion here, here, and many other places).  Integer.valueOf() will return an object from this cache when its argument represents a number in the range.  The comment is warning that parseInt() must not rely on valueOf() because the former may be invoked before that cache is populated.
The misbehavior that could be expected in that case is not specified, and conceivably might vary between Java versions, but plausible possibilities are that null would be returned or an exception (NullPointerException, IndexOutOfBoundsException, ...) would be thrown.
In any case, this is an internal comment in the implementation, not a comment to users of class Integer.  By the time any user code runs, the necessary cache initialization is complete, and Integer.valueOf() can be relied upon to behave fully as its API documentation describes.

A: The source code is (almost) just for reference, the javadoc does not contain that warning because it is only intended for the developers of Java itself.
It is probably a warning since there was some problem or bug caused by someone using the valueOf method to code the parseInt method which can be called before the internal cache is initialized.
In other words, that warning is not intended for you, assuming you are not changing the Integer class!


text:
Q: AWS Lambda: Basic Python Rest API to add 2 numbers and return their sum I'm trying to understand, how to create a REST API using AWS Lambda and Python. For this, I'm creating a simple Lambda function that will accept 2 numbers from the user and return the sum of these numbers.
Code of my Lambda function:
import json

def lambda_handler(event, context):
    # TODO implement
    try:
        #User Input:n1 & n2
        _query = event['queryStringParameters']
        _n1 = int(_query['n1'])
        print(_n1)
        _n2 = int(_query['n2'])
        print(_n2)
        del(_query)

        #Response Body
        _body = {
            'n1': _n1,
            'n2': _n2,
            'sum': _n1+_n2
        }

        print(_body)

        #Response Header
        _header = {
            'Content-Type': 'application/json'
        }

        print(_header)

        #Response
        _response = {
            'statusCode': 200,
            'headers': json.dumps(_header),
            'body': json.dumps(_body)
        }

        print(_response)

        return _response
    except Exception as e:
        print(e)

This Lambda function is connected to AWS API Gateway to allow public access. I have not configured any authentication mechanism for API Gateway.
I'm trying to call this API from another python program.
Source code of calling program:
from requests import get

try:
    _url = 'URL_of_the_lambda_function'
    _params = {
        'n1':1,
        'n2':2
    }

    r = get(
        url=_url,
        params=_params
    )

    data = r.json()

    print(data)
except Exception as e:
    print(e)

This program is getting executed on the terminal with the help of VS Code. When I'm trying to run the program, I'm getting
{'message': 'Internal server error'}

Can anyone please help me to understand, what is the mistake with my code?
[N.B.: As suggested fellow community members:

*

*I have converted header to dictionary.

*I have added try/catch block to both(lambda and calling function)

*I have tried to print every header, response and body objects
]


text:
Q: Which prepositions should I use after "do your best"? I always have been having problems how to understand which preposition to use. Of course there are examples, in which the preposition is obvious. For me the problem occurs when "Do your best in/on/at x." means "Deal with x as effectively as you can.". Which grammar rules or methods should I use for this case?
Examples of phrases I have this problem with include the following:

*

*I'll do my best on the TOEFL preparation so I'll get a higher score on the exam.

*I'll do my best on the test tomorrow.

*Do your best in achieving this goal.

*Do your best in the planning of our weekend.

*Do your best in filling out the form.

The following phrases were changed according to suggestions by Robusto, so now they don't have this problem:

*

*I see these questions for the first time so I haven't prepared for them. Should I just do my best to guess the right answers?

*You will have only 15 seconds to prepare so do your best to use them effectively.

Should I ever write or say "I will do my best at x", when I use it in the meaning "I will cope/deal with x (as good as I will be able to)"?

A: That's a "trick" question because it is not about what follows "best", but simply about "should you use 'in' or 'on'?".
The double-trick is that in some case, you could (with a slight variation of context) use 'for'!

I'll do my best for the TOEFL preparation so I'll get higher score on the exam.

Anyway, if we stick to the initial choice 'in' or 'on', the final trick is in some case, both could be used, like the two first examples ("on" maybe being more commonly used in the US)
I find (personal rule)

*

*"in" standing for "during" or "within" (or other similar meanings)

*"on" standing for "about" or "referenced by" (or other similar meanings)

Meaning I don't find your examples "wrong".

A: Plenty of prepositions can follow "do your best":
Do your best on the test.
Do your best in all your endeavors.
Do your best with the tools you have.
Do your best for the team.

And so on.
Of the examples you give, only these sound awkward to my ear:

Should I just do my best in guessing
  the right answers?
You will have only 15 seconds to
  prepare so do your best in using of
  them.

I would prefer to in those cases:
Should I just do my best to guess the right answers?

You will have only 15 seconds to prepare, so
do your best to use them effectively.

In that last I removed the "of" and added "effectively," which seems clearer and stronger.
EDIT: I removed some examples that wandered away from Preposition Land. Thanks to Ito and fiktor for pointing out my brain cramp.

A: I am not professional in English grammar, but let me share my thoughts about this.
In case of the following:

*

*I'll do my best on the TOEFL preparation so I'll get a higher score
on the exam.

*I'll do my best on the test tomorrow.

*Do your best in achieving this goal.

*Do your best in the planning of our weekend.

*Do your best in filling out the form.

The 'in', 'on' or 'for' can change because they are not the postpositions of the expression 'I'll do my best...', but the prepositions of the expressions afterwards, like 'on the TOEFL' or 'for the TOEFL'. So they don't change according to the preceding part of speech but the following one.


text:
Q: Web service call to XML file content doesn't change when updated in service Have a ASMX web service that manipulates an XML file in a subfolder. This web service is called from another application to do the changing. I have no problem calling the service or making the changes to it. The problem is that the file contents that is returned from the XML is always the same. The web service changes it (verified from looking at the XML file itself).  On another page I use XDocument to get the XML file and load the info into a gridview. The data that gets pushed to the gridview doesn't change even after the XML does. I have turned off caching for the page and viewstate for the gridview. What I can't figure out is how to get it so that the file itself always shows the most recent. Anyone know how to get it so that the XML will always be the latest? Thx.
FYI: IIS can't be touched unless it can be done on this app itself
Edit to show some code of the process that gets the XML file. My apologies in saying it was XDocument when in fact it is a XmlReader.
WebRequest.DefaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
        var newXmlString = _xmlFile + "?nd=" +  + DateTime.Now.ToLongTimeString().Replace(" ", "").Replace(":", "");
        var serializer = new XmlSerializer(typeof(XmlDto.SubscriberData));
        using (var reader = XmlReader.Create(newXmlString))
        {
            var elements = (XmlDto.SubscriberData)serializer.Deserialize(reader);
            if (elements.Subscribers.Count > 0)
            {
                gridSubscribers.DataSource = elements.Subscribers.OrderByDescending(p => p.Name);
            }
            litTotalSubscribers.Text = elements.Subscribers.Count.ToString();
            gridSubscribers.DataBind();
        }

SOLVED or it seems to be after adding
RequestCacheLevel.NoCacheNoStore

it looks to be working correctly. Took awhile for the server to refresh itself and start using the new process but so far everything is being changed and things are coming back with the immediate changes.


text:
Q: Performance of Find() vs. FirstOrDefault()
Similar Question:
Find() vs. Where().FirstOrDefault()

Got an interesting outcome searching for Diana within a large sequence of a simple reference type having a single string property.
using System;
using System.Collections.Generic;
using System.Linq;

public class Customer{
    public string Name {get;set;}
}

Stopwatch watch = new Stopwatch();
    const string diana = "Diana";

    while (Console.ReadKey().Key != ConsoleKey.Escape)
    {
        //Armour with 1000k++ customers. Wow, should be a product with a great success! :)
        var customers = (from i in Enumerable.Range(0, 1000000)
                         select new Customer
                         {
                            Name = Guid.NewGuid().ToString()
                         }).ToList();

        customers.Insert(999000, new Customer { Name = diana }); // Putting Diana at the end :)

        //1. System.Linq.Enumerable.DefaultOrFirst()
        watch.Restart();
        customers.FirstOrDefault(c => c.Name == diana);
        watch.Stop();
        Console.WriteLine("Diana was found in {0} ms with System.Linq.Enumerable.FirstOrDefault().", watch.ElapsedMilliseconds);

        //2. System.Collections.Generic.List<T>.Find()
        watch.Restart();
        customers.Find(c => c.Name == diana);
        watch.Stop();
        Console.WriteLine("Diana was found in {0} ms with System.Collections.Generic.List<T>.Find().", watch.ElapsedMilliseconds);
    }

Is this because of no Enumerator overhead in List.Find() or this plus maybe something else?
Find() runs almost as twice as faster, hoping .Net team will not mark it Obsolete in the future.

A: I'm wagering that FirstOrDefault is running via the IEnumerable implementation, that is, it will use a standard foreach loop to do the checking. List<T>.Find() is not part of Linq (http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx), and is likely using a standard for loop from 0 to Count (or another fast internal mechanism probably operating directly on its internal/wrapped array). By getting rid of the overhead of enumerating through (and doing the version checks to ensure that the list hasn't been modified) the Find method is faster.
If you add a third test:
//3. System.Collections.Generic.List<T> foreach
Func<Customer, bool> dianaCheck = c => c.Name == diana;
watch.Restart();
foreach(var c in customers)
{
    if (dianaCheck(c))
        break;
}
watch.Stop();
Console.WriteLine("Diana was found in {0} ms with System.Collections.Generic.List<T> foreach.", watch.ElapsedMilliseconds);

That runs about the same speed as the first one (25ms vs 27ms for FirstOrDefault)
EDIT: If I add an array loop, it gets pretty close to the Find() speed, and given @devshorts peek at the source code, I think this is it:
//4. System.Collections.Generic.List<T> for loop
var customersArray = customers.ToArray();
watch.Restart();
int customersCount = customersArray.Length;
for (int i = 0; i < customersCount; i++)
{
    if (dianaCheck(customers[i]))
        break;
}
watch.Stop();
Console.WriteLine("Diana was found in {0} ms with an array for loop.", watch.ElapsedMilliseconds);

This runs only 5.5% slower than the Find() method.
So bottom line: looping through array elements is faster than dealing with foreach iteration overhead. (but both have their pros/cons, so just choose what makes sense for your code logically. Furthermore, only rarely will the small difference in speed ever cause an issue, so just use what makes sense for maintainability/readability)

A: I was able to mimic your results so I decompiled your program and there is a difference between Find and FirstOrDefault.
First off here is the decompiled program. I made your data object an anonmyous data item just for compilation
    List<\u003C\u003Ef__AnonymousType0<string>> source = Enumerable.ToList(Enumerable.Select(Enumerable.Range(0, 1000000), i =>
    {
      var local_0 = new
      {
        Name = Guid.NewGuid().ToString()
      };
      return local_0;
    }));
    source.Insert(999000, new
    {
      Name = diana
    });
    stopwatch.Restart();
    Enumerable.FirstOrDefault(source, c => c.Name == diana);
    stopwatch.Stop();
    Console.WriteLine("Diana was found in {0} ms with System.Linq.Enumerable.FirstOrDefault().", (object) stopwatch.ElapsedMilliseconds);
    stopwatch.Restart();
    source.Find(c => c.Name == diana);
    stopwatch.Stop();
    Console.WriteLine("Diana was found in {0} ms with System.Collections.Generic.List<T>.Find().", (object) stopwatch.ElapsedMilliseconds);

The key thing to notice here is that FirstOrDefault is called on Enumerable whereas Find is called as a method on the source list.
So, what is find doing? This is the decompiled Find method
private T[] _items;

[__DynamicallyInvokable]
public T Find(Predicate<T> match)
{
  if (match == null)
    ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
  for (int index = 0; index < this._size; ++index)
  {
    if (match(this._items[index]))
      return this._items[index];
  }
  return default (T);
}

So it's iterating over an array of items which makes sense, since a list is a wrapper on an array.
However, FirstOrDefault, on the Enumerable class, uses foreach to iterate the items.  This uses an iterator to the list and move next. I think what you are seeing is the overhead of the iterator
[__DynamicallyInvokable]
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
  if (source == null)
    throw Error.ArgumentNull("source");
  if (predicate == null)
    throw Error.ArgumentNull("predicate");
  foreach (TSource source1 in source)
  {
    if (predicate(source1))
      return source1;
  }
  return default (TSource);
}

Foreach is just syntatic sugar on using the enumerable pattern. Look at this image
.
I clicked on foreach to see what it's doing and you can see dotpeek wants to take me to the enumerator/current/next implementations which makes sense.
Other than that they are basically the same (testing the passed in predicate to see if an item is what you want)


text:
Q: compare only date and month for conditional column update in sql I have this code in a stored procedure:
d01072016 = case when '07-01-2016' between pp.committedstart and  pp.committedend then 'y'
                 when '07-01-2016' < pp.committedstart then 's'
                 when '07-01-2016' > pp.committedend then 'g' end

based on the date it updates a particular column.
Now I want to compare only date and month so that it becomes year independent.
The date format in SQL Server is mm-dd-yyyy and the table column name is like dd-mm-yyyy but I can always this table column name to match to mm-dd-yyyy.
Please help.


text:
Q: exchange web services: uploading attachment to web server I've been researching this for a while, but I can't find how to tie things together. The scenario is as follows: in order for mobile users to upload images to a website, I am configuring a mailbox on an Exchange 2010 server. The idea is that users mail an image to this mailbox, which is monitored.
As soon as a message is received, the monitoring process should read the e-mail for three things: sender (which is linked to users on the website), subject (which will be added to the image as a description), and attachment (the actual image). The monitoring process should then create a HTTP POST (multipart/form-data) with the three relevant fields from the e-mail and send this to a webserver with a formhandler that expects those three fields and acts accordingly.
Here's what I know so far:

*

*Exchange EWS can give me access to messages and their attachments. I will probably be using ASP.NET for this. I can gain access to the EWS managed services. I have found sample code to work with individual messages.

*Exchange EWS offers triggers to act when new mail arrives, but I haven't found exactly how to implement them.

*I can probably find a way to prepare the form data, sending it to the webserver shouldn't be a problem using winHTTPRequest.

My question is: how to tie all this together. Ideally I write a script (ASP.NET) that reads the message, isolates the attachment, Base64 encodes it, then POSTs it to the webserver. I then write a "rule" that triggers the script whenever a new message arrives on the monitored mailbox.
I would greatly appreciate your help/feedback.


text:
Q: How to run tests while building Python 3.10+ from source? Unlike earlier version 3 releases nowadays building Python 3.10 from source does not seem to run the (time-consuming) tests.
I need to build Python 3.10 on an oldish platform (no, I can't change that). I would actually like to run the tests, even if they are time consuming.
Unfortunately, I can't find the way to do it. Googling shows nonsensical results (how to do testing while using Python, unittest etc), while ./configure --help doesn't show anything.
Have the tests been removed? If not, how can I enable them?

A: Building from source make -j 4 prefix="/usr" usually does the tests too. At least that's what I've observed.


text:
Q: A more efficient way of performing a multiple price changes function I've been wondering if there is a more efficient, and probably neater way of performing an amateur function that I've just coded:
Public Function JanApr_prices()

'catalogue price changes
With ThisWorkbook.Worksheets("catalogue").ListObjects(1)
.DataBodyRange(44, 4).Value = 4.8 'Product A
.DataBodyRange(52, 4).Value = 4.5 'Product B
.DataBodyRange(77, 4).Value = 6 'Product C
.DataBodyRange(79, 4).Value = 9 'Product D
End With

End function

This basically changes prices for a set number of months when I'm doing some accounting. While it works, it definitely has its drawbacks because if I ever changed the relative position of the entries on the table, the price changes would probably go to the wrong place. So I'm in need of another idea, perhaps using a combination of .cells and match? I like to do things neatly and all the solutions that I've thought up so far are rather ponderous. Any suggestions would be greatly appreciated!
Feel free to edit the post title, I really did not know how to describe my problem!

A: The following code is not complete and will have to be adjusted to your needs. It is merely ment to show you the basic concept of the solution I propose.
Public Function JanApr_prices()
Dim vArr As Variant
Dim lCount As Long

vArr = ThisWorkbook.Worksheets("catalogue").ListObjects(1).Range.Value2

For lCount = LBound(vArr) To UBound(vArr)
    Select Case vArr(lCount, 1)
    Case "Produkt A"
        vArr(lCount, 2) = 4.8
    Case "Produkt B"
        vArr(lCount, 2) = 4.5
    Case "Produkt C"
        vArr(lCount, 2) = 6
    Case "Produkt D"
        vArr(lCount, 2) = 9
    End Select
Next lCount

ThisWorkbook.Worksheets("catalogue").ListObjects(1).Range.Value2 = vArr

End Function

The above code was taken from this website and slightly adapted:
https://fastexcel.wordpress.com/2011/05/25/writing-efficient-vba-udfs-part-1/
While I do not like to copy code from the web, StackOverflow prefers to be self-contained without the need to external references. So, there you go.


text:
Q: Convert array into shorter array I have array object -
[
 {
  department:"Reviewer",
  name:"John"
 },
 {
  department:"Reviewer",
  name:"Carol"
 },
 {
  department:"Reviewer",
  name:"June"
 },
 {
  department:"Assistant Reviewer",
  name:"Mac"
 },
 {
  department:"Assistant Reviewer",
  name:"Issac"
 }
]

I want to convert this object into array object as below -
[
     {
      department:"Reviewer",
      name:"John;Carol;June;"
     },
     {
      department:"Assistant Reviewer",
      name:"Mac;Issac;"
     },
]

I tried using filter -
[... new Set(obj.department)].map((item)=>{return {item.name+";"} });

But this operation is dealing with only one element per item. Its not accumulating names.

A: Get a set of distinct departments, then map from them to the list of names

const data = [{"department":"Reviewer","name":"John"},{"department":"Reviewer","name":"Carol"},{"department":"Reviewer","name":"June"},{"department":"Assistant Reviewer","name":"Mac"},{"department":"Assistant Reviewer","name":"Issac"}]

console.log([...new Set(data.map(i=>i.department))].map(i=>({
  department: i,
  name: data.filter(j=>j.department===i).map(j=>j.name).join(';')+';'})))

or, using reduce:

const data = [{"department":"Reviewer","name":"John"},{"department":"Reviewer","name":"Carol"},{"department":"Reviewer","name":"June"},{"department":"Assistant Reviewer","name":"Mac"},{"department":"Assistant Reviewer","name":"Issac"}]

console.log(Object.values(data.reduce((a,{department, name})=>
  (((a[department]??={department,name:''}).name+=`${name};`),a),{})))

A: This would also work:

const input = [ { department: "Reviewer", name: "John", }, { department: "Reviewer", name: "Carol", }, { department: "Reviewer", name: "June", }, { department: "Assistant Reviewer", name: "Mac", }, { department: "Assistant Reviewer", name: "Issac", }, ];

const output = input.reduce((prev, { department, name }) => {
  const match = prev.find((item) => item.department === department);
  if (match) {
    match.name = `${match.name};${name}`;
  } else {
    prev.push({ department, name });
  }
  return prev;
}, []);

console.log(output);

Using Array.prototype.reduce() and Array.prototype.find()

A: Here is a solution using:

*

*.reduce() to build an object that maps from department (aka key) to names (aka value)

*.map() to transform that object into an array of objects with desired format

Note that this solution is faster than an array index search (aka other answers here) for large a large input array, at the cost of using a bit more memory.

const array = [
  { department: "Reviewer", name: "John" },
  { department: "Reviewer", name: "Carol" },
  { department: "Reviewer", name: "June" },
  { department: "Assistant Reviewer", name: "Mac" },
  { department: "Assistant Reviewer", name: "Issac" }
];

const result = Object.entries(array.reduce((acc, obj) => {
  if(acc[obj.department]) {
    acc[obj.department] += obj.name + ';';
  } else {
    acc[obj.department] = obj.name + ';';
  }
  return acc;
}, {})).map(arr => ({ department: arr[0], name: arr[1] }));

console.log(result);

A: This codes should work:

let data = [
  { department: "Reviewer", name: "John" },
  { department: "Reviewer", name: "Carol" },
  { department: "Reviewer", name: "June" },
  { department: "Assistant Reviewer", name: "Mac" },
  { department: "Assistant Reviewer", name: "Issac" }
];

let newData = [];
data.forEach((obj)=>{
  if(newData.filter(m => m.department == obj.department).length) {
    newData.find(n => n.department == obj.department).name += obj.name + ';';
  } else {
    newData.push({
      department: obj.department,
      name: obj.name + ';'
    })
  }
});
console.log(newData);


text:
Q: Convert ASP.NET membership passwords from clear text to hashed We were hashing our passwords, although somewhere along the way one of our developers changed it to clear text so that we could email a user their password if they forgot it.
Anyhow, I'm changing it so that we store passwords 'hashed' now. There is a group of passwords which we need to hash. The salt is already there in the database, I just need to loop through where "passwordformat" = 0 and hash accordingly. How do I do this?
edit: I had a go at a suggestion from another SO post, using "SHA-1" as the hashing algorithm to calculate the digest. It was not the result I expected.
I know the original clear password, the salt, but the result is not what I expected. The answer in the above suggests using SHA-1 as the hashing algo.
If it's any help this is from our web.config of the web server.
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0,

EDIT: I'm getting somewhere. I created another test user, and this time got the same digest value as that generated by the web application. Only difference was the one salt contained '/' symbol, and the other did not. I was not aware that '/' would cause an issue, as I didn't think it's an escape character.
EDIT: here is my code. It works only if the salt does not contain '/'
public static string EncodePassword3(string pass, string saltBase64)
    {

        byte[] bytes = Encoding.Unicode.GetBytes(pass);
        byte[] src = Convert.FromBase64String(saltBase64);
        byte[] dst = new byte[src.Length + bytes.Length];
        byte[] inArray = null;
        Buffer.BlockCopy(src, 0, dst, 0, src.Length);
        Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);

        HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
        inArray = algorithm.ComputeHash(dst);
        return Convert.ToBase64String(inArray);
    }

I can supply the clear text password and salt (only testing at mo) to see if you can get the correct result....


text:
Q: Should I hoard keys for later, or spend them immediately? In Blacksea Odyssey, you'll randomly get keys from the dismembered corpses of alien monsters you've hunted. There are, of course, various chests littered around the map, which have randomized treasure inside them.
I'm curious: do the later levels have better treasure? Or does every treasure chest have the same random equipment, and so I should spend keys just as fast as I find them? (Various levels have bonuses/penalties on the amount of things found in chests – but I want to know if chest quality also depends on the level.)


text:
Q: How to get category discription? This is phtml code for getting selected category. I want to get category description. How can I get that?
<?php
    $catId =2;
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
    $subcats = $subcategory->getChildrenCategories();
?>

  All Categories

        <?php
            foreach ($subcats as $subcat) {
               if ($subcat->getIsActive()) {
                   $subcat_url = $subcat->getUrl();
                   $subcat_img = "";
                   $placeholder_img = "/media/placeholder.png";
        ?>

            <a href="<?php echo $subcat_url; ?>">
                <?php echo $subcat->getName(); ?>

<?php
        }
    }
?>

A: To get the Category Description, you have to load Category and after that, you can use getDescription() function.
I have made some changes in your code. Please find the new code here:
    <?php
        $catId =2;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
        $subcats = $subcategory->getChildrenCategories();
    ?>

  All Categories

            <?php
                foreach ($subcats as $subcat) {

                   if ($subcat->getIsActive()) {
                       $subcat = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
                       $subcat_url = $subcat->getUrl();
                       $subcat_img = "";
                       $placeholder_img = "/media/placeholder.png";
            ?>

                <a href="<?php echo $subcat_url; ?>">
                    <?php echo $subcat->getName(); ?>

<?php echo $subcat->getDescription(); ?>

    <?php
            }
        }
    ?>

Note: In Magento 2, the direct use of ObjectManager in template files is not a good practice. Dependency injection is the recommended approach.
For more details on how to use ObjectManager and what the consequences are of using the ObjectManager directly, you can follow the link below:
https://magento.stackexchange.com/questions/117098/magento-2-to-use-or-not-to-use-the-objectmanager-directly


text:
Q: How to search fraud score for multiple IP's I am trying to find fraud scores for multiple IP's to show in a table
let HttpURL = externaldata (host:string,fraud_score:string, ISP:string,proxy:string,vpn:string,bot_status:string,city:string, country_code:string,tor:string) [h@'https://www.ipqualityscore.com/api/json/ip/jnOFh22KQDTByrHkb4oKQiQBcnNbUOOv/109.96.178.72'] AND [h@'https://www.ipqualityscore.com/api/json/ip/jnOFh22KQDTByrHkb4oKQiQBcnNbUOOv/109.96.178.72']with(format='json');
| project ["HOST IP"] = host,["FRAUD SCORE"]=fraud_score,ISP,PROXY=proxy,VPN= vpn,TOR=tor,["BOT STATUS"]=bot_status,CITY=city,["COUNTRY CODE"]=country_code

I want to add more than one IP but cannot get it to work with the AND to check for the fraud score


text:
Q: Getting closest matching tuple (only lower) from a list of tuples From a list of tuples I want to get the closest for a given value. However I not only want the closest but it must also be lower.
Let me give an example:
my_list = [
  (1, "a"),
  (10, "b"),
  (40, "c"),
  (60, "d"),
]

Let's assume I want to get the closest lower tuple for value 35.
The expected result in this case is [10, "b"]
I have tried the following, but this will return the closest matching, in this case [40, "c"]
value = 35
min(my_list, key=lambda v: value - v[0])

A: You need to return a tuple from your key sorting function.
The min function will compare values using the first element of the tuple (is the value actually lower than the target?) and then use the second element to solve ties (how close is the value to the target?).
value = 35
min(my_list, key=lambda v: (v[0] > value, value - v[0]))


text:
Q: Criar tabela em javascript a partir de um array dinâmico Tenho um array dinâmico onde são adicionados dados a partir de um formulário, porém preciso apresentar os dados em uma table  HTML. Exemplo:
HTML/CSS:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Table</title>

        <button>Get</button>

                    Código
                    Produto
                    Cor

JavaScript:
var conteudo = ["Cód001", "Produto001", "Cor001", "Cód002", "Produto002", "Cor002"]

conteudo.forEach(e => {
  var tbody = document.getElementById('tbody')

  var td = document.createElement('td')

  tbody.appendChild(td)

  td.innerText = e

})

Resultado:
inserir a descrição da imagem aqui
Porém preciso que até o índice 2 do array crie outra linha com o conteúdo restante, por exemplo:
Resultado esperado:
inserir a descrição da imagem aqui

A: Eu copiei seu código,e editei apenas o arquivo JavaScript.
Como você parece ser iniciante, fiz um código mais simples, que você pode refatorar depois de entender a lógica dele.
Pra resolver sua pergunta, você precisa apenas de um array de objetos, onde cada objeto vai ser um produto, assim, quando o forEach mudar de objeto, ele começa na próxima linha da tabela.

const conteudo = [{ cod: 'Cód001', prod: 'Produto001', cor: 'Cor001' },
  { cod: 'Cód002', prod: 'Produto002', cor: 'Cor002' },
  { cod: 'Cód003', prod: 'Produto003', cor: 'Cor003' }];

conteudo.forEach(e => {
  const tbody = document.getElementById('tbody');

  const tr = document.createElement('tr');
  const tdCod = document.createElement('td');
  const tdProd = document.createElement('td');
  const tdCor = document.createElement('td');

  tdCod.innerText = e.cod;
  tdProd.innerText = e.prod;
  tdCor.innerText = e.cor;

  tr.appendChild(tdCod);
  tr.appendChild(tdProd);
  tr.appendChild(tdCor);

  tbody.appendChild(tr);
})
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Table</title>

    <button>Get</button>

            Código
            Produto
            Cor