text:
Q: Delete all files that are set to hidden or read only or system I want to remove all the jpg, ini and more types in current folder and all the sub folders, then delete all the empty folders (recursively). Some of those files are either read only or hidden or even set to system so just the del /s *.jpg doesn't remove them. The problem is it looks like the syntax is using logic and when I do: del /a:h /a:r /s *.jpg so only read only and hidden files are removed but not only hidden files. Is there a way to make it use logic or instead?
I couldn't find examples to make it work without copy pasting the same lines with small changes.
About rmdir, do I have to do cd to the current folder? because it says there's a syntax error in the code below:
del /s *.jpg
del /a:h /a:r /s *.jpg
rmdir /s /q
pause

EDIT3: I think that now it deletes everything with: del /s /f /a:h /a:a *.jpg
I found this for removing empty folders but it doesn't work if the folder is set to read only:
https://superuser.com/a/39679/451485

A: Not tested, but I believe the following will work:
@echo off

:: Remove readonly / hidden / system attributes from all files of interest
attrib -r -h -s *.jpg /s
attrib -r -h -s *.ini /s
rem etc...

:: Delete the files of interest
del /s *.jpg *.ini

:: for each folder, sorted descending by full path (children come before parent)
for /f "delims=" %%F in ('dir /b /ad /s *^|sort /r') do (
  REM check if folder is empty
  dir /b /a "%%F" | findstr "^" >nul || (
    REM remove directory with /S /Q works, even if folder is read only
    rd /s /q "%%F"
  )
)


text:
Q: Get multiple rows value(with input text) from html table and save into DB i had research for this problem but I cant find a solution to fix it. I had a table which retrieve the list of result from Google Book API and display it on a HTML table together with the input textbox. This allow user to multiple select the record and enter the required field so that it can be save into database. Now i stuck on how to retrieve the checked rows value in order to save in database. Can anyone help on this problem?

        <form class="form-horizontal" method="POST" action="">

                  Title
                  Author
                  Publisher
                  Category
                  ISBN
                  Quantity

                  <?php
                    $page = file_get_contents("https://www.googleapis.com/books/v1/volumes?q=%22%22&printType=books&maxResults=40&key=AIzaSyDIY54a21pPyYnXfx8CMJGrf8fdG_Cp-fQ");

                    $data = json_decode($page, true);

                    foreach ($data['items'] as $book) {
                        $Title = $book["volumeInfo"]["title"];
                        $Authors = @implode(",", $book["volumeInfo"]["authors"]);

                        echo "

                          ".'<input type="checkbox" value ="" name="toadd[]" >'."
                          ".$Title."
                          ".$Authors."
                          ".'<input type="text" id="txtPublisher" name="txtPublisher" placeholder="Publisher" >'."
                          ".'<input type="text" id="txtCategory" name="txtCategory" placeholder="Category" >'."
                          ".'<input type="text" id="txtISBN" name="txtISBN" placeholder="ISBN" >'."
                          ".'<input type="text" id="txtQuantity" name="txtQuantity" placeholder="Quantity" >'."

                      ";
                    }
                  ?>

            <button type="submit" class="btn btn-primary btn-flat" name="add" id="add"> Save</button>
        </form>

My exepected is the selected rows value can be retrieve and save into database.This is the image of the HTML table for referenceenter image description here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Передать в обработчик данные собранные с формы, и с обработчика отдать ответ равный 1 или 0 Сделал форму добавления отзыва к товару.
Прикрутил защита от csrf.
В js собираю данные с формы serialize(), и отдаю их в ajax.
В обработчике перед там как добавить данные в БД, с начала проверяю токен, если токен совпадает, то добавляю данные, если нет то возвращаю ответ 0 и останавливаю скрипт.
Если в ajax если все успешно, то вывожу success modal.
Теперь хочу сделать в ajax, если возвращается 0 то вывести окно об ошибке токена, и не выводить success modal. Как это сделать?
Кстати, в форме сделал hidden input с value=0. И в обработчике в последствии присваиваю ему значение 0 либо 1. Сейчас не получается отправить его обратно в ответ в ajax и проверить там и от его значение делать результат во frontend.
Надеюсь я смог донести мысль. Подскажите пожалуйста как решить эту задачу.
Вот код:
$.ajax({
            url: $("#rv_ajax_form").attr('action'),
            type: "POST",
            data: data,
            //dataType: "json",
            success: function( data ) {
                if ( 1 ){
                    $(".rv-success-main").css({"display" : "block"});

                    $(".mymodal").css({"display" : "none"}).fadeOut();
                } else alert("error");

            },

            error: function(response) {
                alert("Ошибка отправки, попробуйте позже.");
            }
        });

Вот php:
$sessid = bitrix_sessid();
if ( $_POST['sessid'] != $sessid ) {
    $_POST['isStatus'] = 0;
    echo $_POST['isStatus'];
    die();
} else {
    $_POST['isStatus'] = 1;
    echo $_POST['isStatus'];
};

A: $.ajax({
    url: $("#rv_ajax_form").attr('action'),
    type: "POST",
    data: data,
    dataType: "json",
    success: function(data) {
        if (data.status){
            alert('success')
            $(".rv-success-main").css({"display" : "block"});

            $(".mymodal").css({"display" : "none"}).fadeOut();
        } else alert("error");

    },

    error: function(response) {
        alert("Ошибка отправки, попробуйте позже.");
    }
});

$sessid = bitrix_sessid();

if ( $_POST['sessid'] != $sessid ) {
    $_POST['isStatus'] = 0;
    echo json_encode(['status' => true]); exit;
} else {
    $_POST['isStatus'] = 1;
    echo json_encode(['status' => false]); exit;
};


text:
Q: Trying to define types with variadic templates I'm brand new to variadic templates, so bear with me here.
I'm trying to bring my dimensional analysis library into the 21st century and up to C++11. I'd like the ability to define a tuple type, not an instance. This is basically what I want to state:
using velocity_dimension = make_dimension<1, 0, -1, 0, 0, 0, 0>;

The result should equivalent to:
using velocity_dimension = std::tuple<std::ratio<1>, std::ratio<0>, std::ratio<-1>, std::ratio<0>, std::ratio<0>, std::ratio<0>, std::ratio<0>>;

I'm struggling to wrap my brain around variadic templates and how to get the interface I want. I've been trying to experiment with:
template<typename T, typename ...Args>
using make_list = std::tuple < std::ratio<T>, make_list<Args>...>> ;

Which I think just illustrates how much I don't understand how these things are supposed to work.

A: You want something that takes a variable number of integers, not types, so there should be no typename in the template parameter list.
Similarly in std::ratio<T> the template argument should be an integer, not a type.
Your recursive  make_list won't work, because you cannot specialize an alias template, so there is no way to terminate the recursion. You could do something like that with a class template and provide a partial specialization to terminate the recursion, but there's no need to do that.
I think you just want:
template<int... I>
  using make_dimension = std::tuple<std::ratio<I>...>;

This takes a parameter pack of integers, then expands it into a list of std::ratio<> specializations and wraps the lot in a tuple.
The pack expansion pattern here is std::ratio<I>... which means each element i in the parameter pack I will be replaced with std::ratio<i>, so if the pack is 1, 2, 3 then the expansion is std::ratio<1>, std::ratio<2>, std::ratio<3>


text:
Q: java.lang.NoSuchMethodError: com.sun.faces.util.Util.isCdiOneOneOrGreater()Z I tried to start web project in jboss using jsf2.2 but the following error occurs:
12:11:40,640 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC000001: Failed to start service jboss.deployment.unit."SuperScreen.war".POST_MODULE: org.jboss.msc.service.StartException in service jboss.deployment.unit."SuperScreen.war".POST_MODULE: JBAS018733: Failed to process phase POST_MODULE of deployment "SuperScreen.war"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:127) [jboss-as-server-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.4.GA-redhat-1.jar:1.0.4.GA-redhat-1]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.4.GA-redhat-1.jar:1.0.4.GA-redhat-1]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_79]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_79]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_79]
Caused by: java.lang.NoSuchMethodError: com.sun.faces.util.Util.isCdiOneOneOrGreater()Z
    at com.sun.faces.application.view.ViewScopeExtension.<init>(Unknown Source)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) [rt.jar:1.7.0_79]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) [rt.jar:1.7.0_79]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) [rt.jar:1.7.0_79]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526) [rt.jar:1.7.0_79]
    at java.lang.Class.newInstance(Class.java:379) [rt.jar:1.7.0_79]
    at org.jboss.as.weld.deployment.WeldPortableExtensions.tryRegisterExtension(WeldPortableExtensions.java:54)
    at org.jboss.as.weld.deployment.processors.WeldPortableExtensionProcessor.loadAttachments(WeldPortableExtensionProcessor.java:119)
    at org.jboss.as.weld.deployment.processors.WeldPortableExtensionProcessor.deploy(WeldPortableExtensionProcessor.java:79)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:120) [jboss-as-server-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14]
    ... 5 more


text:
Q: spring boot + thymeleaf: ... fails to display errors, automatic transition to Login page I have a registration page.  The field data is validated. When errors are captured in the controller's method for user registration and the registration page is called again (where errors should be displayed), an automatic redirect to the /login URL occurs.

org.apache.juli.logging.DirectJDKLog [ERROR] 19:34:25 - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/account/register.html]")] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'userData' available as request attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:153)
at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:926)

spring:
  thymeleaf:
    enabled: true
    check-template-location: true
    prefix: classpath:/templates/
    mode: HTML
    cache: false
    encoding: UTF-8
    suffix: .html

logging:
  pattern:
    console: '%C{1.yaml.} [%-5level] %d{HH:mm:ss} - %msg%n'
  level:
    org:
      hibernate:
        sql: debug
        type:
          descriptor:
            sql:
              BasicBinder: trace

      springframework:
        web:
          client: trace
        security: trace

*

*Registrationcontroller

@Controller
@RequiredArgsConstructor
public class RegistrationController {

    private final UserService userService;

    @GetMapping("/register")
    public String showRegistrationForm(final Model model){
        UserDataDto user = new UserDataDto();

        model.addAttribute("userData", user);
        return "account/register";
    }

    @PostMapping("/register")
    public String userRegistration(final @Valid UserDataDto userData,
                                   final BindingResult bindingResult,
                                   final Model model){
        if(bindingResult.hasErrors()){

            model.addAttribute("errors", userData);
            return "account/register";
        }
        try {
            userService.register(userData);
        }catch (UserAlreadyExistException e){

            bindingResult.rejectValue(
                    "email",
                    "userData.email",
                    "An account already exists for this email."
            );
            model.addAttribute("formreg", userData);
            return "account/register";
        }
        return "redirect:/login";
    }
}

*

*LoginPageController

@Controller
public class LoginPageController {

    @GetMapping("/login-error")
    public String loginError(Model model) {
        model.addAttribute("loginError", true);
        return "login";
    }

    @GetMapping("login")
    public String getLogin(){
        return "account/login";
    }
}

*

*dto

public class UserDataDto {

    @NotEmpty(message = "First name can not be empty")
    private String firstName;

    @NotEmpty(message = "Last name can not be empty")
    private String lastName;

    @NotEmpty(message = "Email can not be empty")
    @Email(message = "Please provide a valid email id")
    private String email;

    @NotEmpty(message = "Password can not be empty")
    private String password;

  ...
}

*

*security config

@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        return http
                .authorizeHttpRequests()
                .requestMatchers("/login", "/register").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login").permitAll()
                .defaultSuccessUrl("/home")
                .failureUrl("/login?error=true")
                .and()
                .build();
    }

    @Bean
    public PasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

*

*account/register.html

<!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">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

            <form action="#" th:action="@{/register}" th:object="${userData}" method="post">

                    <input type="text" class="form-control" th:field="*{firstName}" placeholder="First Name"
                           th:errorclass="is-invalid">

                    <input type="text" class="form-control" th:field="*{lastName}" placeholder="Last Name"
                           th:errorclass="is-invalid">

                    <input type="email" class="form-control" th:field="*{email}" placeholder="Email"
                           th:errorclass="is-invalid">

                    <input type="password" class="form-control" th:field="*{password}" placeholder="Password"
                           th:errorclass="is-invalid">

                    <input type="password" class="form-control" placeholder="Retype password">

                    <button type="submit" class="btn btn-outline-primary  btn-sm btn-block">Register</button>

                            <input type="checkbox" id="agreeTerms" name="terms" value="agree">

                                I agree to the terms

            </form>

        I already have an Account

</script>

*

*account/login.html

<!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">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">

Sign in to start your session

Wrong user or password

                <form th:action="@{/login}" method="post">

                            Invalid username or password.

                        <input type="email" class="form-control" name="username" placeholder="Email">

                        <input type="password" name="password" class="form-control" placeholder="Password">

                            <button type="submit" class="btn btn-primary btn-block">Sign In</button>

                </form>

*

*pom.xml

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/>
    </parent>
 ....
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity6</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

I tried that:

*

*controller

@GetMapping("/handleLoginErrors")
    ModelAndView handleErrors(ModelAndView modelAndView){

        modelAndView.setViewName("account/login");
        return modelAndView;

    }

*

*configuration

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        return http
                .authorizeHttpRequests()
                .requestMatchers("/login", "/register").permitAll()
                .requestMatchers("/account/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login").permitAll()
                .defaultSuccessUrl("/home")
                .failureUrl("/handleLoginErrors").permitAll()
                //.failureUrl("/login?error=true")/**/
                .and()
                .build();
    }

However, the point is to return the errors to the registration page so that the user can see where he made a mistake during registration. That is, to return the user to the registration form and indicate errors in front of the fields where these errors were found.
Who has any ideas how to display errors anyway? And why is there an automatic redirection to /login, and not to the page you specified?

A: Spring will, by default, redirect to login?error (GET)  whenever an error occurs. For login errors, you can, however, change that behaviour by specifying an endpoint (url) that'll handle the login errors. This is done by calling failureUrl.
 return http
            .authorizeHttpRequests()
            .requestMatchers("/login", "/register").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/home")
            .failureUrl("/handleLoginErrors")
            .and()
            .build();

You should also add a controller method matching handleLoginErrors.
 @GetMapping("/handleLoginErrors")
 ModelAndView handleErrors(ModelAndView){
  mv.addObject("loginStatus", "failed");
  mv.setViewName("loginError"); the view name i.e loginError.html
 return mv;

}

Spring also provides several mechanisms for generic error handling. More information can be found here https://www.baeldung.com/exception-handling-for-rest-with-spring.


text:
Q: Release-only exceptions for UWP Storyboard and CallMethodAction I am debugging a piece of code that uses a CallMethodAction to trigger a storyboard in a UWP app. My VS is updated to the latest (15.8.6). The error I am getting from VS 2017 is:

Cannot find method named Begin on object of type
  Windows.UI.Xaml.Media.Animation.Storyboard that matches the expected
  signature.

I have to manually turn on the exceptions in VS, otherwise it will just show:

Unhandled exception at 0x5B79DC3C (Windows.UI.Xaml.dll) in app.exe:
  0xC000027B: An application-internal exception has occurred
  (parameters: 0x1DF30E70, 0x00000003). occurred

After a few tries I found that:

*

*The storyboard works fine in debug. Only crashing in release.

*I go to the definition of the Storyboard, the signature of Begin is:

public void Begin();

Which looks fine. (And it works in debugging...)
The Storyborad and the DataTriggerBehavior is setup like this:
<Storyboard x:Name="ShowOverlay">
  ... // doesn't really matter
</Storyboard>

<core:DataTriggerBehavior Binding="{Binding LogUploadStatus, Converter={StaticResource LogUploadStatusToBoolConverter}, ConverterParameter={StaticResource LogUploadStatusIdle}}" Value="False">
  <core:CallMethodAction TargetObject="{Binding ElementName=ShowOverlay}" MethodName="Begin" />
</core:DataTriggerBehavior>

Does anyone have an idea why the exception only happens in release?

A: In general, instead of CallMethodAction you can use ControlStoryboardAction. This is specific behavior built to support controlling Storyboard element:
<Storyboard x:Name="ShowOverlay">
  ...
</Storyboard>

<core:DataTriggerBehavior Binding="{Binding LogUploadStatus, Converter={StaticResource LogUploadStatusToBoolConverter}, ConverterParameter={StaticResource LogUploadStatusIdle}}" Value="False">
  <core:ControlStoryboardAction Storyboard="{StaticResource ShowOverlay}"
                                ControlStoryboardOption="Play" />
</core:DataTriggerBehavior>

As for why ControlMethodAction didn't work, in Release mode the .NET Native compiler strips away anything that is not used so that it can minimize the size of the resulting assembly and also optimize performance. Unfortunately this can cause problems when using reflection to access types and members which are not accessed anywhere directly.
In this case the Storyboard.Begin() method is never used directly and if you check the source code of CallMethodAction, you can find out the action uses reflection to discover methods on the TargetObject:
foreach (MethodInfo method in this.targetObjectType.GetRuntimeMethods())
{
    ...
}

Luckily there is a way to force the .NET Native compiler to include the type directly and to help you do that you can use the MissingMetadataException Troubleshooter (named by the fact that most of the time this is the exception you will get when a type is missing).
In this case I have put the full path to the Storyboard (Windows.UI.Xaml.Media.Animation.Storyboard) type in A single type section of the tool:

And below chose Access members or activate and Public types and members only.
On the right-hand side the tool will generate the <Type> declaration you will need to add to the <Application> element in Default.rd.xml file you can find in the Properties folder of your UWP project. In our case the result could look like this (excluding comments):
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
  <Application>
    <Assembly Name="*Application*" Dynamic="Required All" />

    <Type Name="Windows.UI.Xaml.Media.Animation.Storyboard" Dynamic="Required Public" />
  </Application>
</Directives>


text:
Q: How can I download zip files with discord.py? Hey I created a command to hash files a user send, but the problem is that I only made this command for me because I need to hash zip files. The problem I have now is that Discord gives an error when it tries to download the zip file (It works fine with other filetypes like .jpg).
Code:
@commands.command()
@commands.has_permissions(administrator=True)
async def hash(self, ctx):
    if ctx.message.attachments:
        attachment = ctx.message.attachments[0]
        embed = discord.Embed(title="Hash",
                              description=attachment.filename,
                              color=discord.Color.blurple(),
                              timestamp=datetime.utcnow())
        await attachment.save(attachment.filename, use_cached=True)
        await asyncio.sleep(3)
        file = attachment.filename

        md5 = hashlib.md5()
        sha1 = hashlib.sha1()
        sha224 = hashlib.sha224()
        sha256 = hashlib.sha256()
        sha384 = hashlib.sha384()
        sha512 = hashlib.sha512()

        list_hash_objects = [md5, sha1, sha224, sha256, sha384, sha512]

        with open(file, 'rb') as opened_file:
            content = opened_file.read()
            for hash_object in list_hash_objects:
                hash_object.update(content)
                embed.add_field(name=hash_object.name,
                                value=f"`{hash_object.hexdigest()}`")

        await ctx.send(embed=embed)
        os.remove(attachment.filename)
    else:
        await ctx.send("No file found!")

Error:
discord.errors.HTTPException: 415 Unsupported Media Type (error code: 0): failed to get asset

It seems like .zip is an unsupported filetype but is there a way to download it? I would be grateful if soemone can help me.


text:
Q: Qt3D/C++: How to stop rendering while updating the Scenegraph I've got a C++/QWidgets application with 2 Qt3DWindow embedded. The 3D windows can be hidden (i.e. the user switches to another view), while work is done in other parts of the application. Whenever the user switches back to the view with the embedded Qt3DWindow there are a lot of changes to be made to the scenegraph.
Rendering is set to OnDemand, but whenever the view is switched back to the 3D windows there is a big lag, up to several seconds. Profiling the application has shown that a lot of work is done for rendering at that point because the scenegraph is changing (most time is spent in the material classes).
My working theory is, that each change to the scenegraph (i.e. removing an entity, adding a new one) causes a separate render update, which leads to the lag due to the amount of separate changes.
So my question is:
Is there a way to stop all render updates until the scenegraph has been updated/modified completely?
I'm thinking of something similar to the beginResetModel() and endResetModel() methods in QAbstractItemModel.


text:
Q: TFS and Microsoft.common.targets assembiles out of sync VS2015 I just upgraded my TFS source to use DevExpress 15.2.5.  However, now I get a bunch of warnings in the output such as
C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3274: The primary reference "C:\Users\User1\Source\Release\V6.1\CommonBin\Release\WebControls.dll" could not be resolved because it was built against the ".NETFramework,Version=v4.5" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v3.5".

and
C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3275: The primary reference "C:\Users\User1\Source\Release\V6.1\CommonBin\Release\WebControls.dll" could not be resolved because it has an indirect dependency on the assembly "DevExpress.Data.v15.2, Version=15.2.5.0, Culture=neutral, PublicKeyToken=7ea533hgx2169hs3" which was built against the ".NETFramework,Version=v4.0,Profile=Client" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v3.5".

along with about 30 other similar warnings.
It's obvious that something is out of sync with my assemblies because they are referencing the wrong versions.  So I looked at my TFS project .csproj file.  The version of DevExpress and .NET framework that are being referenced in there are correct.
I then went to the Microsoft.Common.targets file and opened in Notepad.  I noticed that file is referencing the old version of everything.  How do I get this in sync with my TFS assemblies?

A: It looks like you need to change your project to use the .NET framework version 4.5 on the project properties page:

Word of warning this may result in more warnings or errors depending on the .NET APIs you use.


text:
Q: Can I plug my iPhone 7 directly into the 87W USB C power adapter? I have a lightning connector to USB-C I use for programming and development.

What would happen if I plugged the USB-C end into my late 2016 Mac Book Pro power supply (87 W)?

*Disclaimer, I already did it, and it works. It charges quickly, but not sure if it's safe to do going forward.

A: It will charge. It's not dangerous. That power adapter is designed to supply UP TO 87W. If you plug a 15" tbMBP into it, it will draw all 87W provided. If you plug a 13" tbMBP into it, the MBP will only draw 61W, even though the adapter can provide 87W. Same for you iPhone. It will draw the amount of power it needs (~10W, IIRC), and the adapter has no problem providing only that amount of power.
However, it is interesting to note that the USB plug adapters that come with iPhones provide only 5W, iPhones are capable of pulling more power, and will charge faster when plugged into an iPad (10W) or tbMBP USB plug adapter.

A: It will work just fine and won't damage it.
It will charge your iPhone just fine with 2.1 Ampere until it reaches 80 % battery charge. After that point it will charge at a lower rate (also called "trickle charge").
Your iPhone controls how much energy will be drawn, not the charger.

You'd get same behavior if you charge it

*

*connected to a MacBook Pro Retina (or newer) using a USB port

*using the 2.1A/12W charger from the iPad


text:
Q: How to filter items by some value using filter form? I have items, that have price, color, manufacturer, model and so on. I want users to filter items by price range, manufacturer, model at the same time. For example: show all cars with manufacturer "Ford", model "Mustang" and price from 1k to 10k.
For pagination results i want use will_paginate (and submit form with ajax). I am looking for some "first bricks" or "first steps" to solve my problem. If i miss some good new tutorials, pls, feel free to give links :)

A: Do something like this with a where query in your controller:
@records = Stuff.select("stuffs.*")

@records = @records.where("model = ?", model) if filter_car
@records = @records.where("price >= ? and price <= ?", price) if filter_price
@records = @records.paginate(:page => params[:page], :per_page => params[:per_page])


text:
Q: Sql Server Building query from variables declare @String varchar(max),
        @Stat varchar(3),
        @Statval int

SET @Stat = 'STR'
SET @Statval = 500

set @String = 'UPDATE [Addpoints] SET ['+@stat+'] = ['+@stat+'] + '+@statval+''

SELECT @String

I'm trying to build query inside @String from some variables. But i'm getting error - 'Conversion failed when converting the varchar value 'UPDATE [Addpoints] SET ' to data type int.'
At the end i want @String to be like this
@String = 'Update [Addpoints] SET [STR] = [STR] + 500'

A: Your query would not be safe enough. Use this instead:
DECLARE @String NVARCHAR(MAX)
    , @Stat VARCHAR(3) = 'STR'
    , @Statval INT = 500;

SET @String = N'
    UPDATE A
    SET A.' + QUOTENAME(@Stat) + N' += @Statval
    -- SELECT *
    FROM dbo.Addpoints AS A;';

PRINT @String;

EXECUTE sys.sp_executesql @SQL, N'@Statval INT', @Statval;

This query will generate following:
UPDATE A
SET A.[STR] += @Statval
-- SELECT *
FROM dbo.Addpoints AS A;

Keep in mind that [STR] = [STR] + 500 is exactly the same as [STR] += @Statval, it's just a nice shorthand.
As you can see column names are quoted. QUOTENAME() does that for you and escapes illegal characters. And sp_executesql let's you create parameterized queries, which are safe and their execution plans are cached.
In your case @Statval will be assigned a value of 500.

A: You have to cast int values to varchar ones explicitly when you're combining them into string:
set @String = 'UPDATE [Addpoints] SET [' + @stat + '] = [' + @stat + '] + ' +
               cast(@statval as varchar(max))

A: Two solutions:

*

*Cast your statval to varchar as pointed by Andy

*or, If you have the ability, you can declare your statval directly as a  varchar


text:
Q: How to set PTR record on Windows Server 2008? I'm having some problems sending out emails from my SMTP Server... apparently I need to setup the PTR record for Reverse-DNS Lookups.
I have no clue how to do this.

Some instructions point ask to

*

*go to Administrative Tools

*click on DNS
there is no item called DNS within Administrative Tools!

Any ideas?

A: The owner of the public ip address block that your server gets it's public ip address from needs to set up the PTR record.

A: Well, to answer the question you're asking, you need to install DNS on that server before you can configure DNS on that server. If you need to do this on Windows 2008, it is configured as a windows 2008 role. So just choose to add a role from the Windows 2008 management tools, select DNS and go from there.
There will still be some work to set DNS up before you can just add your PTR record - you will need to create a forward zone to manage your domain name and associated records, and should really be creating PTR/reverse lookup records for all hosts.
However, Before you do that consider this: your server must presumably already be pointing to a DNS server somewhere, which may be one owned by your ISP/webhost and just refers to the IP addresses you use generically, or it may be one that manages a block of IPs and a domain name for your Internet presence specifically - it is this DNS server that needs a PTR record configuring for your mail server, so investigate this before trying to install and configure your own DNS.


text:
Q: How to fix error Emulator error after build/run android aosp (just show a black screen) I tried to compile and test android aosp following these steps:
1. clone android aosp ([https://source.android.com/setup/build/downloading][1] )
2. lunch 2
3. m -j8
4. emulator

After that, emulator just show a black image as follow:

I don't know if are missing step to build and run android aosp code.
there is one suggestion to fix it ?
Thanks in advance


text:
Q: GTK2 themes do not show up in any tweak tool I have Ubuntu 14.04 and I would like to download this theme
I managed to get it to work on 13.10 but since I upgraded to 14.04 it no longer works. When I look in any tweak tool it does not show up. Other themes that I copied into ~/.themes and also /usr/share/themes work just fine. The only difference as far as I can tell is those themes that work have both a gtk-2.0 and a gtk-3.0 folder, while this theme "A New Hope" only has a gtk-2.0 folder.
edit: Well, I guess the theme is just not gtk3 compatible, is the answer. But is there any way around this?


text:
Q: Adding a RHV Provider to Cloudform with User not privileged I need to update the user admin of the RHV provider by another User. Is this possible ?, or what attributes does a different user need to have to work well with Cloudform?
References:
In the section 8 of 1.2.1 the information isn't clear: https://access.redhat.com/documentation/en-us/red_hat_cloudforms/4.2/html-single/managing_providers/index
It works well with user admin@internal, but not is mentioned if another user (users of RHV) can connect to the RHV from Cloudform.
Thanks in advance,
Kind Regards,
Javier


text:
Q: Some questions about resolvable group divisible designs In the context of some other construction (which is irrelevant here), I was looking for a way to generate a collection "orthogonal partitions" on a set of nodes with a fixed and uniform set size, and I wanted it to be scalable in the number of partitions and nodes.
Example
On the set $\{0,...,8\}$ one can easily find such an arrangement by putting the numbers into a 3x3 grid (with "wrap around", like a torus), and separately take the rows, columns and both diagonals, getting the following 4 "orthogonal set covers / partitions":

*

*$\{\{0,1,2\},\{3,4,5\},\{6,7,8\}\}$

*$\{\{0,3,6\},\{1,4,7\},\{2,5,8\}\}$

*$\{\{0,4,8\},\{1,5,6\},\{2,3,7\}\}$

*$\{\{2,4,6\},\{1,3,8\},\{0,5,7\}\}$
which satisfy the desired properties (uniform + orthogonal partitions).
Research I did
I figured out that this is connected to variants of combinatorial designs. I found MOLS, the Wikipedia article also shows how to convert a MOLS via Orthogonal Arrays into a "net", which looks like (a subclass of) what I want. I also found this code and learned how to easily generate MOLS(n) for prime n.
So for a prime $n \in \mathbb{N}$, I can generate $(n-1)$ MOLS and transform those into $(n+1)$ different partitions $n^2$ nodes, using sets of size $n$, so that the partitions are "orthogonal" in the sense above.
I also randomly stumbled on the social golfer problem, which finally led me to resolvable group divisible designs - that looks like exactly the kind of definition I was looking for.
So apparently, what I am actually interested in, are RGDDs with $\lambda=1$ (i.e. intersect at most in 1 element between sets of different partitions), and more precisely, families of RGDDs with fixed and singleton $K$ (i.e. uniform block size), but variable $\nu$ (i.e. number of elements).
Questions
My background is computer science, I have no deep background in combinatorics or statistics (where apparently most "designs" are used), and there is a confusingly large number of related concepts and names for what I'm looking for. So I wonder if I found everything useful and/or interesting about existence and construction of such sets.

*

*Is there something known about effectively and systematically constructing RGDDs of that type for sets different from the MOLS-based approach / finite field constructions for prime numbers?

*Is there a already working algorithm or implementation for generating RGDDs of the type I want which also directly works with powers of primes?

*What is known about RGDDs for (powers of) composite numbers?
Mostly I am interested in "constructable" results (ideally, with constructions that don't need me to be an expert in combinatorics or finite field theory), but "(non)-existence" results are also good to know for orientation.
Furthermore, I believe that I managed to build a recursive construction that takes a set of "base RGDDs" (e.g. obtained from MOLS), and lifts them to larger node sets. For example, for the "base" 3, I take the RGDD in the example above (which is the solution for size $3^2$) and lift it to produce for any $i\in\mathbb{N}$, an RGDD with $3^i$ nodes and $3^{i-1}$ groups, each with $3^{i-1}$ blocks of size 3.
I have not proved it yet (just ran multiple tests for different parameters), but at least by Theorem 2.2 of that paper what I am doing looks at least plausible and like an iterated "RGDD multiplication" (at least it matches with the expected parameters of the RGDD according to the theorem), in fact it is actually "exponentiation".

*Is this known/folklore/trivial, or is there already some paper explaining in more detail how to practically generate such families, or a library/implementation that can do that? Or would it be interesting if I write up the concrete algorithm I came up with and try proving it? In fact, I found the mentioned paper/theorem after having my construction, so I am not yet sure how/whether it relates to the actual steps in the proof.

The field-based construction might yield the complete set of partitions for prime powers ($p^k+1$ should be possible, right? from $p^k{-}1$ MOLS($p$)), but I cannot fully understand or implement it, and have not seen it implemented in full generality in the wild, and it results in increasingly larger block sizes anyway, while I want to keep mine fixed). So I thought that maybe a different construction for a different variation could be interesting.
If this is something new and non-trivial, this might motivate me to try fleshing it out and writing it up (and maybe to try to generalize it even further).
Would be happy to get some gentle orientation in the sea of combinatorics that I accidentally stumbled into!


text:
Q: DevicePolicyManager.lockNow(); doesn't turn off screen when security settings are set to Slide/None The user expects my app to switch off the screen after being used. At the moment, I achieve this with Device Administrator rights and DevicePolicyManager.lockNow(), which works fine if the security settings are set to PIN/Pattern/FaceUnlock, etc.
However, if using Slide/None, the above command just takes the user to the homescreen (or doesn't do anything), which is understandable, since there's nothing to "lock". Is there any way to achieve turning off the screen in such a situation? My app requires SDK>=16, if that matters.
So I guess my question is: How can an app reliably switch off the screen (I'm not holding a wakelock, I'm using the WindowManager-flags FLAG_TURN_SCREEN_ON in onAttachedToWindow()).
The "flow" of my app is:
- Activity is started by an intent while the screen is off, shows above the keyguard/switches on the screen with the above-mentioned flags
- User actively dismisses my Activity, I'm calling lockNow() and finish() and the user expects the screen to turn off. If the user is using the none/slide lock, this doesn't work and instead the user's homescreen is shown
Thanks!

A: To begin with see here:

To control this policy, the device admin must have a "force-lock" tag
  in the "uses-policies" section of its meta-data.
The calling device admin must have requested USES_POLICY_FORCE_LOCK to
  be able to call this method; if it has not, a security exception will
  be thrown.

Depending from the code you got, here's a pretty nice explanation of what can be wrong in your case (of course any code provided here will be of use!).
I've heard on several occasions, that calling twice the code DevicePolicyManager.lockNow() will do the trick and here's one way of doing that:
mDPM = (DevicePolicyManager)getApplicationContext().getSystemService("device_policy");
Handler handlerUI = new Handler();
      handlerUI.postDelayed(new Runnable() {
          @Override
          public void run() {
              mDPM.lockNow();
          }
      }, 200);
      finish();
      mDPM.lockNow();

Here I found a more elaborate version of the same thing:
Android DevicePolicyManager lockNow() problem
public class SMSMessagingActivity extends Activity {
    /** Called when the activity is first created. */

public static DevicePolicyManager mDPM;

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

        mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);

    }

    public static void LockNow(){
        mDPM.lockNow();
    }

}

ComponentName devAdminReceiver; // this would have been declared in your class body
// then in your onCreate
    mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
    devAdminReceiver = new ComponentName(context, deviceAdminReceiver.class);
//then in your onResume

boolean admin = mDPM.isAdminActive(devAdminReceiver);
if (admin)
    mDPM.lockNow();
else Log.i(tag,"Not an admin");

Let's hope that the last workaround will work correctly.
Cheers

A: I used Delyan's comment to achieve this:

If you request WRITE_SETTINGS, you can probably set the screen timeout to be 1 sec - android.provider.Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000); Of course, then you're messing up the user's settings but I can't figure out a better way to do it. I have seen apps that do it - NoLED is the most prominent example.


text:
Q: MongoDB lookup with match not efficient in large amount of data I have a two collection that systems and systemsToUsers. It is refer the systems _id as a foreign key system_id in a systemToUsers table. I need system data which all are _id not presents in the sytemToUser table.
I am using the below query but it is taking a long time (5 seconds) for 100 000 data. But need to optimize the query reduce the execution time
    db.Systems.aggregate([
    { $lookup: {
from: 'systemsToUsers',
localField: '_id', foreignField: 'system_id',
as: 'systemswithusers' } },
    { $match: { $expr: { $eq: [ { $size: '$systemswithusers' }, 0 ] } } }
  ]);

A: Try below $match and make sure every column in aggregate have index.
db.Systems.aggregate([
  {
    $lookup: {
      from: "systemsToUsers",
      localField: "_id",
      foreignField: "system_id",
      as: "systemswithusers"
    }
  },
  {
    $match: {
      systemswithusers: []
    }
  }
])

mongoplayground


text:
Q: MS Band continue reading values on lockscreen I try to read accelerometer values from the band even if

*

*The phone is locked

*The app hasn't the focus

Reading values while the app has the focus works quite well.
But if I press the "Windows" button and working on other apps, no ChangedEventArgs will be fired anymore.
I would like to collect accelerometer and gyro data over the whole day to determin what the user who is wearing the band is doing. (Pattern recognition for eating, drinking etc.)
Is this possible with the default Microsoft.Band SDK?
My code
            IBandInfo[] pairedBands = await BandClientManager.Instance.GetBandsAsync();
            IBandClient bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);
            if (bandClient.SensorManager.HeartRate.GetCurrentUserConsent() != UserConsent.Granted)
            {
                await bandClient.SensorManager.Gyroscope.RequestUserConsentAsync();
            }

            bandClient.SensorManager.Gyroscope.ReadingChanged += Gyroscope_ReadingChanged;
            await bandClient.SensorManager.Gyroscope.StartReadingsAsync();

A: The application must be running continuously in order to stream sensor data continuously from the Band.  On Windows Phone that generally means the application is in the foreground and in active use; applications can stream sensor data in the background but, for battery life reasons, background tasks have strict limitations on the frequency and duration with which they execute.  Very few applications are allowed to operate continuously (e.g. streaming media applications).
In any case, having an active Bluetooth connection to the Band for an extended period of time would likely be a significant drain on the Band's battery.  For the sake of your users, you will likely want to identify other triggers that indicate when the user may be engaging in a particular activity, and then only streaming sensor data for those brief periods of time.

A: Instead of using a TimeTrigger background task, you could explore the DeviceUseTrigger to get a "near-permanent" connection to the band. While I haven't tried it myself, below article details the necessary steps. I think it is a feasible approach considering your requirements?
http://www.codeproject.com/Tips/1036512/Achieveing-Indefinite-Background-Execution-with-th


text:
Q: .net: How to execute a stored procedure with a nullable parameter in c#? How to execute a stored procedure with a nullable parameter in c#?
EDIT:
Actually, I've written below code. As you can see, status parameter is a nullable value type.
Is it correct? or not?
public void LoadAll(DataTable tb, int? status=null)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection())
            {
                connection.ConnectionString = this.connectionString;

                using (SqlCommand command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "USP_OrganizationChartSelect";
                    SqlCommandBuilder.DeriveParameters(command);
                    command.Parameters["@Status"].Value = status.HasValue ? status : null;
                    if (connection.State != ConnectionState.Open)
                        connection.Open();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    tb.Clear();
                    adapter.Fill(tb);
                    adapter.Dispose();
                    adapter = null;
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Thanks

A: You could try DBNull.Value instead of null or omit the parameter when the nullable has no value entirely.

A: If the parameter is nullable, it must be a value type. Suppose you have an int nullable parameter, then you can pass it this way..
  int? nullableParam = null;
  nullableParam = 10; //set the value if any
  //Pass nullableParam to your sp call.

A: you can check the nullable value in your sp like below:
select * from table
where (code = @code or @code is null)

by this solution if @code be null then this condition will not apply.


text:
Q: Count on Spark Dataframe is extremely slow I'm creating a new DataFrame with a handful of records from a Join.
val joined_df = first_df.join(second_df, first_df.col("key") ===
second_df.col("key") && second_df.col("key").isNull, "left_outer")
joined_df.repartition(1)
joined_df.cache()
joined_df.count()

Everything is fast (under one second) except the count operation. The RDD conversion kicks in and literally takes hours to complete. Is there any way to speed things up?
INFO MemoryStore: Block rdd_63_140 stored as values in memory (estimated size 16.0 B, free 829.3 MB)
INFO BlockManagerInfo: Added rdd_63_140 in memory on 192.168.8.52:36413 (size: 16.0 B, free: 829.8 MB)
INFO Executor: Finished task 140.0 in stage 10.0 (TID 544). 4232 bytes result sent to driver
INFO TaskSetManager: Starting task 142.0 in stage 10.0 (TID 545, localhost, executor driver, partition 142, PROCESS_LOCAL, 6284 bytes)
INFO Executor: Running task 142.0 in stage 10.0 (TID 545)
INFO TaskSetManager: Finished task 140.0 in stage 10.0 (TID 544) in 16 ms on localhost (executor driver) (136/200)
INFO ShuffleBlockFetcherIterator: Getting 0 non-empty blocks out of 200 blocks
INFO ShuffleBlockFetcherIterator: Started 0 remote fetches in 0 ms
INFO ShuffleBlockFetcherIterator: Getting 0 non-empty blocks out of 200 blocks
INFO ShuffleBlockFetcherIterator: Started 0 remote fetches in 0 ms

A:
Everything is fast (under one second) except the count operation.

This is justified as follow : all operations before the count are called transformations and this type of spark operations are lazy i.e. it doesn't do any computation before calling an action (count in your example).
The second problem is in the repartition(1) :
keep in mind that you'll lose all the parallelism offered by spark and you computation will be run in one executor (core if your are in standalone mode), so you must remove this step or change 1 to a number propositional to the number of your CPU cores (standalone mode) or the number of executors (cluster mode).

The RDD conversion kicks in and literally takes hours to complete.

If I understand correctly you would covert the DataFrame to an RDD, this is really a bad practice in spark and you should avoid such conversion as possible as you can.
this is because the data in DataFrame and Dataset are encoded using special spark encoders (it's called tungstant if I well remembered it) which take much less memory then the JVM serialization encoders, so such conversion mean that spark will change the type of your data from his own one (which take much less memory and let spark optimize a lot of commutations by just work the encoded data and not serialize the data to work with and then deserialize it) to the JVM data type and this why DataFrames and Datasets are very powerful than RDDs
Hope this help you

A: As others have mentioned, the operations before count are "lazy" and only register a transformation, rather than actually force a computation.
When you call count, the computation is triggered. This is when Spark reads your data, performs all previously-registered transformations and calculates the result that you requested (in this case a count).

The RDD conversion kicks in and literally takes hours to complete

I think the term "conversion" is perhaps a bit inaccurate. What is actually happening is that the DataFrame transformations you registered are translated into RDD operations, and these are applied to to the RDD that underlies your DataFrame. There is no conversion per se in the code you have given here.
As an aside, it is possible to explicitly convert a DataFrame to an RDD via the DataFrame.rdd property. As mentioned in this answer this is generally a bad idea, since you lose some of the benefits (in both performance and API) of having well-structured data.


text:
Q: MBP 6.1 compatibility with 14.04 LTS I installed 14.04 LTS on my MBP 6.1 (early 2010) and everything works flawlessly except for when I let my laptop go to sleep.
It wakes up, but when I try to log back in, it just crashed and reboots. Anyone encounter this issue and/or solved this issue?
Thanks in advance!

A: This thread might give you hints http://ubuntuforums.org/showthread.php?t=2145047. Some guys switched to nvidia-experimental or the proprietary video driver and reinstalled apport.


text:
Q: MPMoviePlayerController: Didn't get sound when we stop MPMoviePlayerController I am using MPMoviePlayerController to play a video into my application. Below is my code for playing video.
    **NSURL *url=[[NSURL alloc] initFileURLWithPath:urlPath];
    if(moviePlayer)
    {
        [moviePlayer.view removeFromSuperview];
        moviePlayer = nil;
    }

    moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
    moviePlayer.repeatMode = MPMovieRepeatModeOne;
    moviePlayer.currentPlaybackTime = 0.0;
    moviePlayer.view.frame = _viewMoviePlayer.frame;
    moviePlayer.controlStyle    =       MPMovieControlStyleNone;
    moviePlayer.shouldAutoplay = YES;
    [_viewMoviePlayer addSubview:moviePlayer.view];
    [moviePlayer prepareToPlay];
    [moviePlayer play];
    [self.view sendSubviewToBack:_viewMoviePlayer];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];**

When viewWillDisappear called, then I just stop moviePlayer and remove it from view. But my default music player is running but didn't sound for it. When I closed my application, it will.
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [moviePlayer stop];
    [moviePlayer.view removeFromSuperview];
    moviePlayer = nil;

    [_viewMoviePlayer removeFromSuperview];
    _viewMoviePlayer = nil;
}

Can anyone tell which is going wrong in my code? So I am release the moviePlayer then it will play default music as it should. when I check current sound for Music then its ohk and also its show song is running in Music app. But didn't get sound.

A: I faced with same issue. I just created one separate controller. Below is my code for same:
-(void)playVideo
{
   isPlay = FALSE;
   if([[MPMusicPlayerController systemMusicPlayer] playbackState] == MPMoviePlaybackStatePlaying)
       isPlay = TRUE;

   NSString *urlPath = [[NSBundle mainBundle]
                        pathForResource:@"all"
                        ofType:@"mp4"];

   NSURL *url=[[NSURL alloc] initFileURLWithPath:urlPath];

   if(player)
       [player pause];

   player = nil;

   if(avPlayerLayer)
       [avPlayerLayer removeFromSuperlayer];

   AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:url];
   player = [[AVPlayer alloc] initWithPlayerItem:playerItem];

   avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:player];

   avPlayerLayer.frame = self.view.frame;
   [self.view.layer addSublayer:avPlayerLayer];
   [player play];
  }

-(void)removeMoviePlayer
{
   if(isPlay)
       [[MPMusicPlayerController systemMusicPlayer] play];
   NSError *deactivationError = nil;
   BOOL success = [[AVAudioSession sharedInstance] setActive:NO error:&deactivationError];
   if (!success) {
       NSLog(@"%@", [deactivationError localizedDescription]);
   }
}

Hope it will helpful to you... :)


text:
Q: Is it possible to redirect stdin/stdout with go:generate I have a tool that acts as a pipe, it reads data from stdin and writes go source code to stdout.
Is it possible to setup input/output redirection and use such tool with go:generate? Something like:
//go:generate tool < file.txt > file.go

A: I figured out how to do it:
//go:generate sh -c "tool < file.txt > file.go"


text:
Q: MUI data grid boolean cell type conditional formatting Is there a way to conditionally format MUI datagrid cell that has a 'boolean' type.
Here is a sandbox from documentation with a checkbox column that has a boolean type: https://codesandbox.io/s/1ckfjp?file=/demo.tsx:1771-1855
const columns: GridColumns = [
    ...
    {
      field: 'isPaid',
      headerName: 'Is paid?',
      type: 'boolean',
      width: 140,
      editable: true,
    },
    ...

Is using cellRender (in cols definition (https://mui.com/x/react-data-grid/column-definition/#rendering-cells)) the only way to render my own green or red icons depending if value is true or false? Or is there a better way?

A: So far this seems the easiest way:
const columns: GridColumns = [
    ...
    {
      field: 'isPaid',
      headerName: 'Is paid?',
      type: 'boolean',
      width: 140,
      editable: true,
      renderCell: (params) => {
        return params.value ? (
          <CheckIcon
            style={{
              color: theme.palette.success.light,
            }}
          />
        ) : (
          <CloseIcon
            style={{
              color: grey[500],
            }}
          />
        );
      },
    },
    ...


text:
Q: renaming an admin menu item with decimal array index number I am trying to rename a menu item on my administration dashboard.
Using the $GLOBALS['menu'], I have found the following array indexes

[26.0648] => Array  (    [0] => M.E. Calendar ...

and

[26] => Array       (    [0] => Products ...

After using the following code:
global $menu;
global $submenu;
$menu[26.0648][0] = 'Event Calendar';

The result is that the "M.E. Calendar" item has not changed, whereas the Products item has changed to

[26] => Array
          (
              [0] => Event Calendar
              [1] => edit_products
              [2] => edit.php?post_type=product

Is there a way I can rename the menu item with the decimal array index number? Thanks.

A: You have to use a string as key:
$menu['26.0648'][0] = 'Event Calendar';

If you write the key as a number, it will truncate the decimal to an integer, so 26.0648 will be truncated to 26.


text:
Q: Multiple range inputs related on number from parent I have 4 range inputs. Each of them has min number 0, max number 10.
In Total they can't sum to more than 22.
One way to approach this would be to disable all inputs once they hit 22 and add a reset button. I would find it to be more user-friendly to allow the ranges to be decremented after the max is reached instead of a whole reset.
I tried disabling if it's less or equal 0, but the scroller was still under control.
Check the comments on the
sandbox here if it easier , but the parent class is as below:
<template>

Left: {{ hmLeft }} votes

        <userVoteFor :hmLeft="hmLeft" @cntCount="cntCount"  :id="user._id"/>

</template>

Child class here:
<template>

    {{ playerNameById( id )}}
    <input @input="check($event)" // thought maybe something to do with event ?
           :disabled="disable"
           class="vote__component__input"
           :id="id"
           type="range"
           min="0"
           max="10"
           step="1"
           v-model="cnt">

{{ cnt }}

</template>

A: The way I'd implement this is by using a watch and the get and set method of computed.
The array of values would be updated via a computed. This makes it easy to hook into a v-model and allows us to maintain reactivity with the original array.
The watch is then used to compute the total that is available. Then, for bonus points, we can use the total to adjust the width of the input so the step size remains consistent.
Even though this is using the composition Api, you can implement that using data, watch and computed the classical way

const makeRange = (max, vals, index) => {
  const defaultMax = 10;
  const num = Vue.computed({
    get: () => vals[index],
    set: value => vals[index] = Number(value)
  });
  const total = Vue.computed(() => vals.reduce((a, b) => a + b, 0), vals);
  const style = Vue.computed(() => {
    return `width: ${(numMax.value * 12 + 20)}px`
  })

  const numMax = Vue.computed(() => {
    return Math.min(defaultMax, (num.value + max - total.value))
  }, total);

  return {num, numMax, style};
};

const app = Vue.createApp({
  setup() {
    const vals = Vue.reactive([5, 5, 5])
    const max = 22;
    const ranges = vals.map((v,i)=>makeRange(max, vals, i));

        // helpers for visualising
    const total = Vue.computed(() => vals.reduce((a, b) => a + b, 0), vals);
    const totalLeft = Vue.computed(() => max - total.value , total.value);

    return {ranges, vals, totalLeft, total, max};
  }
}).mount('#app');

    <input
      :style="range.style.value"
      type="range" min="0"
      :max="range.numMax.value"
      v-model="range.num.value"
    >
    value: {{range.num.value}}
    max: {{range.numMax.value}}

{{ vals.join(' + ') }} =  {{ total }}

max is {{ max }} , minus total {{total }} is {{ totalLeft }}


text:
Q: Multiple tables join issue in sequelize in node js I have 6 tables
Employees,Salary,Deduction,DeductionTypes,Allowance,AllowancesTypes
Here is the table relations with a diagram

I can't understand how to create a join query
Employee.belongsTo(Salary, {  foreignKey: 'employee_id' });
Salary.belongsToMany(Deduction,    {foreignKey: 'salary_id' });
Deduction.belongsToMany(DeductionType,    {foreignKey:   'deduction_type_id' });
Salary.belongsToMany(Allowance,    {foreignKey: 'salary_id' });
Allowance.belongsToMany(AllowanceType,    {foreignKey: 'allowance_type_id' });

Here is my find query
const payRunData = Employee.findAll({
    include: [{
        model: Salary, attributes: ['salary_id', 'basic_salary'],
        include: [
            {
                model: Deduction, attributes: ['amount'],
                include: [{
                    model: DeductionType, attributes: ['epf_enable', 'type', 'pre_tax', 'pay_run_editable'],
                }]
            },
            {
                model: Allowance, attributes: ['amount'],
                include: [{
                    model: AllowanceType, attributes: ['epf_enable', 'type', 'payee_enable', 'pay_run_editable'],
                }]
            }
        ]
    }
    ],
    attributes: ['employee_id', 'given_names'],
});

Here is the sql join query what I'm expecting
select s.salary_id , e.employee_id, e.given_names, d.amount as 'deduction_amount',
dty.`type` as 'deduction_type', dty.epf_enable as 'deductType_epf_enable', dty.pre_tax, dty.pay_run_editable as 'deductType_pay_run_editable',
a.amount as 'allowance_amount', aty.`type`as 'allowanceType_type', aty.epf_enable as 'allowanceType_epf_enable',
aty.payee_enable  as 'allowanceType_payee', aty.pay_run_editable as 'allowanceType_pay_run_editable'
from employees as e inner join salary as s on e.employee_id = s.salary_id
inner join deductions as d on  s.salary_id = d.salary_id
inner join deduction_types as dty on d.deduction_type_id = dty.deduction_type_id
inner join allowances as a on  s.salary_id = a.salary_id
inner join allowance_types as aty on a.allowance_type_id = aty.allowance_type_id

When I execute this,it's returning this error

salary.belongsToMany(deduction) requires through option, pass either a
string or a model"

please help me  to solve this


text:
Q: How to convert a SQL query to Spring JPA query I have a SQL query like this:
"Select UIProfileID from UserTable where UPPER(UserID) = UPPER('?1')".
I want to convert it to Spring JPA.
I want to write getUIProfileId() and return Integer. But I don't know how to implement. Because User table doesn't have UIProfileId column that it was joined from UIProfileTable table. Please help me solve it.
Currently, I have tables:
User.java
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Table(name = "UserTable")
public class User {

  @Column(name = "UserID", length = 32, nullable = false)
  @Id
  private String name;

  @ManyToOne
  @JoinColumn(name = "DomainID", nullable = false)
  private Domain domain;

  @Column(name = "Password", length = 32, nullable = false)
  private String password;

  @ManyToOne
  @JoinColumn(name = "UIProfileID", nullable = false)
  private UIProfile uiProfile;

  @Column(name = "ResPerpage", nullable = false)
  private Integer resperpage;

  @Column(name = "DefaultTab")
  private Integer defaulttab;

  @ManyToOne
  @JoinColumn(name = "AdminProfile")
  private AdminProfiles adminProfile;

  @Column(name = "LanguageId")
  private Integer languageId;
}

UIProfile.java
@Entity
@Getter
@Setter
@Table(name = "UIProfileTable")
public class UIProfile implements Serializable {

  @Id
  @Column(name = "UIProfileID", length = 11, nullable = false)
  private Integer id;

  @Column(name = "UIProfileName", length = 32, nullable = false)
  private String name;

  @OneToMany(mappedBy = "id.uiProfile")
  private List<UIProfileTopLevel> topLevels;
}

UserRepository.java
public interface UserRepository extends Repository<User, String> {

  Optional<User> findOne(String name);

  @Query("Select UIProfileID from User where UPPER(UserID) = UPPER('admin')")
  Integer getUIProfileId();

}

A: You can try this:
@Query("SELECT u.uiProfile.id from User u where UPPER(u.name)=UPPER('admin')")
Integer getUIProfileId();

Here User is the domain class name and u is the reference of User. with u we will access User's field NOT the column name which are specified with @Column or @JoinColumn Ex : @JoinColumn(name = "UIProfileID", nullable = false).


text:
Q: Cache and use only one object in case of equality - equal objects should get referneces I have a KeyObject consuming some fair amount of memory. The KeyObject also has a hashValue and an equals Method implemented.
Now I want to hold every unique KeyObject only once in my memory and just use references to this object in case of equality (equals not ==).
I thought I could use a Set but I can not get the original KeyObject. I can only replace the existing one with a new one.
Here is what I mean in pseude code:
Keybject a = new Keybject("a");
Keybject b = new Keybject("a");
boolean thisIsTrue = a.equals(b);
boolean thisIsFalse a == b;

Map<KeyObject, Value> largeMapA = new HashMap<>();
Map<KeyObject, Value> largeMapB = new HashMap<>();

largeMapA.put(a, "value a");
largeMapB.put(b, "value b");

Now I have the large KeyObject twice -> one for each largeMap, but it would be enough to have  only one KeyObject (a.equals(b)) and use a reference for the the 2nd map.
So I want something like this:
KeyObject b = if there is already a equal object ("a") in my "cache" then use "a"
largeMapA.put(a, "value a");
largeMapB.put(b, "value b"); // Now I have ONE large KeyObject
                             // this is just a reference to a

The only only solution that comes in mind is to loop the entry largeMapA and find a equal key then replace b:
for (KeyObject ko : largeMapA.keySet()) {
  if (ko.equals(b)) {
    b = ko;
    break;
  }
}

But this seems not to be a performant solution ...

A: You can use a HashMap<KeyObject,KeyObject> in which the key is the same as the value.

*

*if (map.contains(b)) will tell you if your cache contains the key.

*map.get(b) will give you that key.

*if the map doesn't contain the key, you put it there - map.put(b,b)


text:
Q: Promise.all in not waiting to finish the inner Promise.all completion let obj = [
  {
    Id: 1,
    name: 'david',
    Address:[{
      city: 'dubai',
      country: 'UAE'
    }]
  },
  {
    Id: 2,
    name: 'Ram',
    Address: [{
      city: 'US',
      country: 'India'
    },
    {
      city: 'Delhi1',
      country: 'India1'
    }]
  }
];

async function fun() {
await Promise.all(obj.map(async info => {
      console.log('info', JSON.stringify(info));
      await Promise.all(info.Address.map(async (items, index) => {
        console.log('ParentItems IsParentLossCapability',);
        let pr = await firstFunction();
        console.log('promise resolved: ' + pr)
        console.log('next step');
      }));
      console.log('UpdatedInfo', JSON.stringify(obj));
    }));
}
 async function firstFunction() {
  return new Promise((resolve, reject) => {
    let y = 0;
    setTimeout(() => {
      for (let i = 0; i < 10; i++) {
        y++;
      }
      console.log('loop completed');
      resolve(y);
    }, 2000);
  });
 }

fun();

What I am getting output like below, it says

*

*info

*info

*loop completed

*promise resolved

*next step

*UpdatedInfo

*Loop completed

*next step

*UpdatedInfo

It should give output like this,

*

*info

*loop completed

*Promise resolved: 10

*next step

*UpdatedInfo

*info

*loop completed

*promise resolved: 10

*next step

*UpdatedInfo

A: When you use .map(async (e) => {...}), all the functions start executing at the same time. await Promise.all(arr.map(async (e) => {...})) waits for all of them to finish, but it's still parallel.
What you want is to make them sequential. Either you can use a for loop:
for (let info of obj) {
      console.log('info', JSON.stringify(info));
      for (let index = 0 ; index < info.Address.length; index++) {
      let items = info.Address[index];
        console.log('ParentItems IsParentLossCapability',);
        let pr = await firstFunction();
        console.log('promise resolved: ' + pr)
        console.log('next step');
      }
      console.log('UpdatedInfo', JSON.stringify(obj));
}

or use an async reduce:
await obj.reduce(async (memo, info) => {
      await memo;
      console.log('info', JSON.stringify(info));
      await info.Address.reduce(async (memo2, items, index) => {
        await memo2;
        console.log('ParentItems IsParentLossCapability',);
        let pr = await firstFunction();
        console.log('promise resolved: ' + pr)
        console.log('next step');
      }), Promise.resolve());
      console.log('UpdatedInfo', JSON.stringify(obj));
    }, Promise.resolve());


text:
Q: host a WCF services which returns a list of instances of a datacontract I'm new to visual studio. I create a datacontract about book information. I create a WCF web services parsing a txt file and create a list of instance of that book information.
When I was trying to call this service to get book information and displace on a web form. I found I don't know how to access Datamember of those instance. Can anybody help me?
public interface IService1
{
    [OperationContract]
    List<Book> GetAllBooks();
    [OperationContract]
    String SearchBookById();
}

[DataContract]
public class Book
{
    [DataMember]
    public int Num { get; set; }
    [DataMember]
    public string ID { get; set; }
    [DataMember]
    public string name { get; set; }
    [DataMember]
    public string author { get; set; }
    [DataMember]
    public int year { get; set; }
    [DataMember]
    public float price { get; set; }
    [DataMember]
    public int stock { get; set; }
}

public List<Book> GetAllBooks()
{
    var bookList = new List<Book>();
    int n = 1;

    StreamReader reader = new StreamReader(@"C:\infs 7204\prac3\books(1).txt");
    {
        string fileLine;
        while((fileLine = reader.ReadLine())!= null)
        {
            string[] bookInfo = fileLine.Split(',');
            int year = Int32.Parse(bookInfo[3]);
            float price = float.Parse(bookInfo[4].Trim('$'));
            int stock = Int32.Parse(bookInfo[5]);
            bookList.Add(new Book { Num = n, ID = bookInfo[0], name = bookInfo[1], author=bookInfo[2],
            year=year,price=price, stock=stock});
            n++;

        }
    }
    return bookList;
}

I need to display those book classes in a table on my webpage. Here is how I want to access the datacontract list. But I got an warrning says "Cannot implicitly convert type'prac3.ServiceReference1.Book[] to 'prac3.Book[]'"
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Service1Client client = new Service1Client();
        Book[] list= client.GetAllBooks();

    }
}

Also, Is there any segesstion about which conponent in toolbox should I use to display the table?

A: Try to include the full namespace of Book and see if it works.
Have you added a project reference to the Book class and generated a service reference also? If that's thje case, better remove the project reference and let svcutil generate a common namespace with ädd service reference".
List<prac3.ServiceReference1.Book> books = client.GetAllBooks();

foreach (prac3.ServiceReference1.Book book in books)
{
  Console.WriteLine(book.author);
}

A: Your warning Cannot implicitly convert type'prac3.ServiceReference1.Book[] to 'prac3.Book[] indicates that very likely you have duplicate definition of type Book.
There are two possibilities:

*

*More likely, as Servé Laurijssen has already pointed out, your client project might have a project reference to your service project. Hence you have access to all of the public types defined within it (including Book.) To be sure if your client project has reference to service project: open your client project in Visual Studio, in Solution Explorer expand the References node under your client project, and find if your service project's name appear there.

*Or, less likely, you have redefined class Book in your client project.

In both cases, you get two definitions of Book: one prac3.Book (defined in service project) and another prac3.ServiceReference1.Book (generated by service reference in client project, usually in the file Service References\Service Namespace Name\Reference.cs under your client project directory.) In your case, you are trying to set a prac3.ServiceReference1.Book array to a prac3.Book one, hence causing a type mismatch.
For an immediate remedy change the following line in your client code
Book[] list= client.GetAllBooks();

to the following
prac3.ServiceReference1.Book[] list= client.GetAllBooks();

And consider removing the reference to the service project or the duplicate definition. It is very unusual a client has reference to a service assembly that it refers as well.


text:
Q: How to fill a fillable word 2010 document with c# How can I create a instance of a existing MS Word 2010 template (the template has only 1 textbox), get the fillable field and insert a string in there?
All this in c#, so far i couldn't even open a .docx document.

A: It's not free, but I've done this with Syncfusion (on WinRT once).
You can set a bookmark, then navigate to that bookmark in c# and replace its content (strings, images, tables, etc.).
http://www.syncfusion.com/
docu: http://help.syncfusion.com/winrt (DocIO is what you are searching for)
They have a free trial, but maybe you can find something similar (replacing bookmarks, if you can't get the fillable) for free (I didn't, but only searched for WinRT)

A: I was able to do that with those libraries:
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
using Vladimir.Classes_Auxiliares;

These fields:
public object Template;
public Object oFalse = false;
public Object oTrue = true;
public Object oMissing = System.Reflection.Missing.Value;

And these methods. First one is to open the Word application (Visible = false), and create a new document based on a saved template.
public virtual Word.Document CriarDocumento(ETipoDeDocumento tipoDeDocumento, Word.Document doc, Word.Application word)
        {
            Template = tipoDeDocumento.ToString() + ".dotm";
            doc = word.Documents.Add(Template, ref oMissing, ref oMissing, ref oMissing);

            return doc;
        }

The next method will look for text and objects the the content or words matches the Dictionary keys to fill the active document with values I wanted represented by the Dictionary where the key is the same as the strings in the template and the value is the new value I want to pass to the new document.
    public virtual void PreencherDocumentoPorObjetoETexto(Dictionary<string, string> listaDeParametros, Word.Document doc)
    {
        foreach (Shape shape in doc.Shapes)
        {
            foreach (string key in listaDeParametros.Keys)
            {
                if (shape.TextFrame.TextRange.Text.Contains(key))
                    shape.TextFrame.TextRange.Text = listaDeParametros[key];
            }
        }

        foreach (string key in listaDeParametros.Keys)
        {
            Word.Find findObject = doc.Application.Selection.Find;
            findObject.ClearFormatting();
            findObject.Text = key;
            findObject.Replacement.ClearFormatting();
            findObject.Replacement.Text = listaDeParametros[key];

            object replaceAll = Word.WdReplace.wdReplaceAll;
            findObject.Execute(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref replaceAll, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
        }

    }

This method will finally show the Word application in a print preview state with the print dialog opened. Only options are print or cancel.
    public virtual void ImprimirDocumento(Word.Application word)
    {
        word.PrintPreview = true;
        word.Visible = true;

        Word.Dialog wordPrintDialog = word.Application.Dialogs[Word.WdWordDialog.wdDialogFilePrint];
        wordPrintDialog.Show(ref oMissing);
    }

This method should be called every time you open a document using those methods, it will close the document and the Word application.
    public virtual void FecharDocumento(Word.Document doc, Word.Application word)
    {
        System.Threading.Thread.Sleep(1000);

        doc.Close(oFalse, oMissing, oMissing);
        word.Quit(oFalse, oMissing, oMissing);
        Marshal.FinalReleaseComObject(doc);
        Marshal.FinalReleaseComObject(word);
    }

If you don't finish the Word application using the method above, I recommend you to call the Task Manager and finish the instance manually.


text:
Q: Claims added to ClaimsIdentity getting lost in ASP.NET Core Identity System In my ASP.NET Core Identity I have noticed that my claim that I add are getting lost.
First I have a Create claim view having a form to create a claim. The claim is added to the currently logged in user.
The code of the Action method is:
[HttpPost]
[ActionName("Create")]
public IActionResult Create_Post(string claimType, string claimValue, string claimIssuer)
{
    ClaimsIdentity identity = User.Identity as ClaimsIdentity;
    Claim claim = new Claim(claimType, claimValue, ClaimValueTypes.String, claimIssuer);
    identity.AddClaim(claim);
    return RedirectToAction("Index");
}

The clain is added on this line - identity.AddClaim(claim);.
Now the last line is redirecting to Index action method whose code is:
public ViewResult Index() => View(User?.Claims);

The Index View which is showing all the claim for the user is:
@model IEnumerable<System.Security.Claims.Claim>

        Subject
        Issuer
        Type
        Value

    @foreach (var claim in Model.OrderBy(x => x.Type))
    {

            @claim.Subject.Name
            @claim.Issuer
            @claim.Type
            @claim.Value

    }

Example: I added a claim, see the below image

But the Index View did not fetched the claim, see the below image:

What is wrong?

A: If you want to save the claims to User?.Claims, you need to call _signInManager.Context.SignInAsync with updated ClaimsIdentity.
Follow steps below:

*

*Extension for signin with new ClaimsIdentity
public class CustomClaimsCookieSignInHelper<TIdentityUser> where TIdentityUser : IdentityUser
{
private readonly SignInManager<TIdentityUser> _signInManager;

public CustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager)
{
    _signInManager = signInManager;
}

public async Task SignInUserAsync(ClaimsIdentity claimsIdentity)
{
    await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme, new ClaimsPrincipal(claimsIdentity));
}

}

*Register CustomClaimsCookieSignInHelper<TIdentityUser>
services.AddTransient<CustomClaimsCookieSignInHelper<IdentityUser>>();

*Update User Claims
public class IdentityController : Controller
{
private readonly CustomClaimsCookieSignInHelper<IdentityUser> _signInHelper;
private readonly UserManager<IdentityUser> _userManager;
public IdentityController(CustomClaimsCookieSignInHelper<IdentityUser> signInHelper
    , UserManager<IdentityUser> userManager)
{
    _signInHelper = signInHelper;
    _userManager = userManager;
}
public ViewResult Index() => View(User?.Claims);

[HttpGet]
[ActionName("Create")]
public IActionResult Create_Post()
{
    return View();
}

[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> Create_Post(string claimType, string claimValue, string claimIssuer)
{
    ClaimsIdentity identity = User.Identity as ClaimsIdentity;
    Claim claim = new Claim(claimType, claimValue, ClaimValueTypes.String, claimIssuer);
    identity.AddClaim(claim);
    await _signInHelper.SignInUserAsync(identity);

    return RedirectToAction("Index");
}
 }

A: Claims added to a authenticated user will not persisted through others requests. Claims must be added before login.
You can take a look here to see how to add claims to the user.
And here for an example on how to change user claims after login.


text:
Q: How to add multiple Media from Disk in Laravel Spatie Media Library? I'm saving images from local disk to cloud (DO storage) disk by following codes in controller
$claim->addMediaFromDisk($front_image, 'public')->usingFileName("front-image")->toMediaCollection('claim-images', 'do_spaces');
$claim->addMediaFromDisk($right_image, 'public')->usingFileName("right-image")->toMediaCollection('claim-images', 'do_spaces');
$claim->addMediaFromDisk($left_image, 'public')->usingFileName("left-image")->toMediaCollection('claim-images', 'do_spaces');

this trick works but saving those images in 3 different directory in cloud storage. But I want all three images in same directory.
I see there is built in method for adding multiple media from request. But how can I do it form disk. I was expecting something like addMultipleMediaFromDisk(!). Is there any solution ?
Laravel version: 7.30
Spatie media library version: 7.20

A: //where the original file is saved on the local disk and the conversions on S3.
$media = $claim->addMedia($pathToImage)->storingConversionsOnDisk('s3')
->toMediaCollection('claim-images', 'local');


text:
Q: Wrong white background when converting SVG to PNG with gradient I want to convert SVG images to PNG keeping transparency. In the case of solid color shapes works fine, but when the shape is filled with a gradient, then the output image renders an unexpected solid white background.
I want some solution using Imagick library, but some code to preproccess svg code is also acceptable.
Here a minimal example of the issue:
<?php
$svg = <<<SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="100" height="100">
   <ellipse style="fill:red" cx="50" cy="50" rx="50" ry="50" />
</svg>
SVG;

$img = new \Imagick();
$img->readImageBlob($svg);
$img->setImageBackgroundColor('transparent');

//IMAGE WITH NICE TRANSPARENT BACKGROUND
$img->writeImage(__DIR__ . '/circle_plain.png');

$svg = <<<SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="100" height="100">
  <defs>
    <linearGradient
       id="linearGradient1">
      <stop
         style="stop-color:#ff0000;stop-opacity:1;"
         offset="0"/>
      <stop
         style="stop-color:#00ff00;stop-opacity:1;"
         offset="1"/>
    </linearGradient>
    <linearGradient
       xlink:href="#linearGradient1"
       id="linearGradient2"
       x1="0"
       y1="50"
       x2="100"
       y2="50"
       gradientUnits="userSpaceOnUse" />
  </defs>
  <ellipse style="fill:url(#linearGradient2)" cx="50" cy="50" rx="50" ry="50" />
</svg>
SVG;

$img = new \Imagick();
$img->readImageBlob($svg);
$img->setImageBackgroundColor('transparent');

//IMAGE WITH WRONG WHITE BACKGROUND!!
$img->writeImage(__DIR__ . '/circle_gradient.png');


text:
Q: insert into multiple tables with register form i have a register form and I tried to insert information into multiple tables but that second query doesn't work , i know i have to use user_id for second one but can someone explain to me how?
    $sql="INSERT INTO users(firstname,lastname,email,password) VALUES('$firstname','$lastname','$email','$password')";

    $sql2="INSERT INTO address(phone,city,address) VALUES('$phone','$city','$address')";

$result=mysql_query($sql);
if($result){
echo "Account Successfully Created";
} else {
echo "Failure!";
}

A: A quick/dodgy solution would be:
 $sql="INSERT INTO users(firstname,lastname,email,password) VALUES('$firstname','$lastname','$email','$password')";
 $result = mysql_query($sql);

if($result){
    $userid = mysql_insert_id();
    $sql2="INSERT INTO address(userid, phone,city,address) VALUES($userid, '$phone','$city','$address')";
    $result = mysql_query($sql2);
}

You should use the newer mysql functions though - mysqli
 http://php.net/manual/en/book.mysqli.php as mysql is deprecated.
If you decide to stick with mysql though - at the very least mysql_real_escape those values :)


text:
Q: Plotting andrews curves of subsets of a data frame on the same plot I have a data frame of 12 columns and I want to plot andrews curves in R of this data, basing the color of the curves on the 12th columns. Below are a few samples from the data (sorry the columns are not aligned with the numbers)
Teacher_explaining  Teacher_enthusiastic    Teacher_material_interesting    Material_stimulating    Material_useful Clear_marking   Marking_fair    Feedback_prompt Feedback_clarifies  Detailed_comments   Notes   Year
80  80  80  80  85  85  80  80  80  80  70  3
70  60  30  40  70  60  30  40  70  0   30  3
100 90  90  80  80  100 100 90  100 100 100 MSc
85  85  85  90  90  70  90  50  70  80  100 MSc
90  50  90  90  90  70  100 50  80  100 100 4
100 80  80  75  90  80  80  50  80  80  90  3

From this data I tried to plot andrews curves using the code below:
install.packages("andrews")
library(andrews)

 col <- as.numeric(factor(course[,12]))
    andrews(course[,1:12], clr = 12)

However, the 12th column has three groups (3 types of responses) and I want to group two of them and then plot the andrews curve of the data, without editing my data frame in Excel.
x <- subset(course, Year == "MSc" & "4")
y <- subset(course, Year == "3")

I tried the above code, but my argument for x don't work. "MSc", "3" and "4" are the groups in the 12th column, and I want to group MSc and 4 so that their Andrews curves have the same color.
If you have any idea how to do this, please let me know.

A: You may try to collapse levels 'MSc' and '4' in the 'Year' variable into one level. I call your data frame 'df':
# convert 'Year' to factor:
df$Year <- as.factor(df$Year)

# rename the levels. 'MSc' and '4' is collapsed into a new level with name MSc_4
levels(df$Year) <- list(MSc_4 = c("MSc", "4"), "3" = c("3"))

# plot
andrews(df = df, clr = 12)


text:
Q: How can I search all plugins for composer's vendor/autoload.php? I've got projects (both themes and plugins) set up as composer projects. These projects can be dev-dependencies of each other. Right now I'm working on a theme which requires the vendor/autoload.php file. However, when I bring that theme into another project (like a plugin), I still need access to the autoload.php. The problem is that the autoload.php file is now inside the directory structure for the plugin and not the theme.
define('FL_CHILD_THEME_DIR', get_stylesheet_directory());
define('FL_CHILD_THEME_URL', get_stylesheet_directory_uri());

if (!file_exists(FL_CHILD_THEME_DIR . '/vendor/autoload.php')) {
  // somehow check all the directories within the plugins directory
  // for vendor/autoload.php
} else {
    require FL_CHILD_THEME_DIR . '/vendor/autoload.php';
  }
}

I've tried using things like scandir and glob but I'm not getting any closer. I thought something like this would work, but I'm still no closer.
foreach(glob(plugin_dir_path() . 'vendor/autoload.php') as $file {
  require $file;
}

A: Autoloader setup:
"autoload"   : {
   "files"   : ["functions.php"]
}

Once you have the autoloader setup properly, you just need to include that one file, like this:
require_once( 'vendor/autoload.php' );

Full tutorial here - https://torquemag.io/2014/11/improving-wordpress-plugin-development-composer/


text:
Q: smooth out corners of a 3-point line strip I have a line strip defined by 3 points, each having an x and y coordinate.
I'm trying to smooth out the middle (point 2) corner as shown in the picture below:

the gray line is the original line strip and the black one is the smoothed-out one.
The smoothed out area should be constant across multiple values (as in it is not dependent on length of the line between p1 and p2 or p2 and p3).
I've originally been using bezier curves and a simple spline, however that did not do the trick since the smooth curve was obviously not same across multiple values.
How can I do this?

A: Pick 2 points on each line that are the same distance to the corner. On those points draw two lines at right angles to the lines you already have (normal vectors pointing bottom left). They will cross at a point which will be the center of a circle, part this circle will then be the smoothed corner.


text:
Q: Why is this call ambiguous for compiler? I am experimenting with async/await and I am getting compiler error for DoWorkAsync1.
Error   CS0121  The call is ambiguous between the following methods or properties: Task.Run<TResult>(Func<TResult>) and Task.Run<TResult>(Func<Task<TResult>>)
For DoWorkAsync2 I added typecast to advice the compiler and that is OK. Why it has problems with DoWorkAsync1? DoWorkAsync3 does the same, only the function is anonymous and it has no problem too.
static int Pom() { return 42; }

static async Task<int> DoWorkAsync1()
{
    var operation = Task.Run<int>(Pom);
    return await operation;
}

static async Task<int> DoWorkAsync2()
{
    var operation = Task.Run<int>( (Func<int>)Pom );
    return await operation;
}

static async Task<int> DoWorkAsync3()
{
    var operation = Task.Run<int>(() => 42);
    return await operation;
}

A: The reason why you're getting this is that the return-type is not taken (enough) into account when determining overload candidates in C# 7.2 or older. As such, the list of potential candidates does not contain only 1 method, and the compiler halts with an ambiguity error.
This was improved on in C# 7.3:

*

*For a method group conversion, candidate methods whose return type doesn't match up with the delegate's return type are removed from the set.

This also explains why your lambda works, it is not a method group conversion, a different part of the compiler kicks in and is apparently able to determine the correct overload.
And indeed, if I compile your code with C# 7.0, 7.1 or 7.2, I get:

[CS0121] The call is ambiguous between the following methods or properties: 'Task.Run<TResult>(Func<TResult>)' and 'Task.Run<TResult>(Func<Task<TResult>>)'

... but if I change it to 7.3, it compiles, and is using the Func<int> overload.


text:
Q: How to load a function after the Script Manager? On code behind I have this code:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "FetchFacebook", "FetchFeeds('facebook');", true);

and inside the javascript function FetchFeeds() I do a call to a WebServer. The JS reference to it it's on the ScriptManager, which is registered on the page after the code behind.
So when I call FetchFeeds there isn't yet the webservice reference.
How can I choose when to call FetchFeeds() from codebehind?


text:
Q: Regex select text excluding certain characters I have a text like this
MyText.xyz;
MyText.abc + "ss";

I want to capture text which comes after MyText., but does not end with ; or empty space, i.e. I want the output like:
MyText.xyz
MyText.abc

I have created this regex: MyText.(.*(?=\;)) in order to achieve my goal.
But, right now the text matching out from regex is MyText.xyz and MyText.abc + "ss", i.e. the second result is incorrect.

A: You may fix it using a negated character class:
MyText\.[^\s;]+
        ^^^^^^^

See the regex demo
Regex details

*

*MyText\. - a literal MyText. substring (note the . must be escaped to match a literal . char)

*[^\s;]+ - a negated character class matching any 1+ chars other than whitespace (\s) and ; char

Use it as var pattern = @"MyText\.[^\s;]+"; in C#.

A: MyText\..+?\b(?<!;)
   ^  ^ ^  ^  ^
   |__|_|__|__|______ MyText : "MyText" literal
      |_|__|__|______ \.     : "." literal, escaped by "\"
        |__|__|______ .      : any character
           |__|______ ?\b    : non-greedy search up to boundary (\b)
              |______ (?<!;) : not ended by ';'

Test:
$ cat sample.txt
MyText.xyz;
MyText.abc + "ss";
MyText.uuu+"yyy";

$ grep -Po 'MyText\..+?\b(?<!;)' <sample.txt
MyText.xyz
MyText.abc
MyText.uuu

Note: It's based on solution of @Wiktor Stribiżew, with looking behind added

A: You are using
MyText.(.*(?=\;))

The first mistake is the . after MyText, it should be \. if you want to match a literal dot.
The second half is also incorrect, you're trying to match any number of non-linebreaking-characters, followed by a ;, which is why you got the results you did.
Try this regex instead:
MyText.[^ ;]*

The [^ ;]* matches any character that is not a space or a ;. If you also don't want tabs or linebreaks to match, you can use the following instead:
MyText.[^\s;]*

\s matches any whitespace character.


text:
Q: Update MongoDB Driver for WebStorm plugin I'm trying to use the "Mongo Plugin" within WebStorm on OSX.  Two collections in my database are listing successfully within the IDE, but when I try to open other collections I receive error messages such as:

org.bson.BsonSerializationException: Detected unknown BSON type "\x13" for fieldname "myfield.  Are you using the latest driver version?

The field generating this error message is the type BigDecimal, which is relatively new.  I've confirmed the path to my mongo shell is correct within the plugin at /usr/local/bin/mongo.
What should I do to update the driver?  I have researched this problem and know the location of the MongoDB drivers, but I have no idea which one to update for the plugin (or how).
Also, I verified any versions of Mongo through homebrew and npm are updated. These are probably not relevant.
NPM -g:
npm install -g mongodb
/usr/local/lib
└─┬ mongodb@2.2.22
  ├── es6-promise@3.2.1
  ├─┬ mongodb-core@2.1.7
  │ ├── bson@1.0.4
  │ └─┬ require_optional@1.0.0
  │   ├── resolve-from@2.0.0
  │   └── semver@5.3.0
  └─┬ readable-stream@2.1.5
    ├── buffer-shims@1.0.0
    ├── core-util-is@1.0.2
    ├── inherits@2.0.3
    ├── isarray@1.0.0
    ├── process-nextick-args@1.0.7
    ├── string_decoder@0.10.31
    └── util-deprecate@1.0.2

Brew:
brew install mongo
Warning: mongodb-3.4.2 already installed

Also the version of Mongo on the target server:
mongo --version
MongoDB shell version v3.4.1
git version: 5e103c4f5583e2566a45d740225dc250baacfbd7
OpenSSL version: OpenSSL 1.0.1t  3 May 2016
allocator: tcmalloc
modules: none
build environment:
    distmod: debian71
    distarch: x86_64
    target_arch: x86_64

A: Thanks to the link provided by LazyOne, I discovered the plugin simply does not provide support for the Decimal type through this issue as of this date.


text:
Q: Using coroutine channels and the livedata builder together How might I use coroutine channels together with the livedata coroutine builder (androidx.lifecycle:lifecycle-livedata-ktx architecture component) to continuously listen for messages produced from a websocket library to a ReceiveChannel<String>?
My first thought is to implement it like this
val user: LiveData<String> = liveData {
    while(true) {
        val data = myWebsocketChannel.receive() //Channel suspend function
        emit(data)
    }
}

But this feels a bit "non-kotliny" and my gut is telling me that there is a better of solving this.
Is there a better way of handling posting data once received from a coroutine channel?

A: I would write it like this:
val user: LiveData<User> = liveData {
    myWebsocketChannel.consumeEach { data ->
       emit(data)
   }
}

myWebsocketChannel.consumeEach { ... } is going to iterate forever (suspending, if channel is empty) until someone closes the myWebsocketChannel. On the producer side - where we are listening to the socket, we should be careful to not close channel prematurely.
Hope it helps :)


text:
Q: Slick Grid: Slick grid using with Bootstrap popup calendar issue I am using slick grid with Bootstrap . I have a slick grid in my page and onclik of a button of that page one Bootstrap pop up will open thenin that popup I have to choose a date to insert in that cell. My calendar is coming but in behind the popup.
What should I do.

A: Please add the follwing code in your page to solve the issue
here ui-datepicker-div is a id so hash symbol need to prefix
ui-datepicker-div
{ z-index: 99999 !important; /* must be > than popup editor (950) */ }