text:
Q: How to register dependency of generic repository? I have the following repository base:
public class FakeRepositoryBase<TEntity, TPrimaryKey> : AbpRepositoryBase<TEntity, TPrimaryKey>
    where TEntity : class, IEntity<TPrimaryKey>
{...}

And inherited from the first:
public class FakeRepositoryBase<TEntity> : FakeRepositoryBase<TEntity, int>, IRepository<TEntity>
    where TEntity : class, IEntity<int>
{...}

Module registration:
[DependsOn(typeof(AbpKernelModule))]
public class DERCFakeDALModule: AbpModule
{
    public override void Initialize()
    {
        IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
    }
}

Then I declare AppService:
class DocumentAppService : ApplicationService, IDocumentAppService
{
    private readonly IRepository<Document> _documentRepository;
    private readonly IObjectMapper _objectMapper;

    public DocumentAppService(
        IRepository<Document> documentRepository,
        IObjectMapper objectMapper)
    {
        _documentRepository = documentRepository;
        _objectMapper = objectMapper;
    }

    // AppService methods
}

And add all the dependencies to my WebModule:
[DependsOn(
        typeof(AbpWebMvcModule),
        typeof(DERCApplicationModule),
        typeof(DERCWebApiModule),
        typeof(DERCFakeDALModule))]
public class DERCWebModule : AbpModule

After calling any API method, there is an error:
{
  "message": "An error has occurred.",
  "exceptionMessage": "ComponentActivator: could not proxy Abp.WebApi.Controllers.Dynamic.DynamicApiController`1[[DERC.ApplicationServices.Interfaces.IDocumentAppService, DERC.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]",
  "exceptionType": "Castle.MicroKernel.ComponentActivator.ComponentActivatorException",
  "stackTrace": "   в Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext context, ConstructorCandidate constructor, Object[] arguments)\r\n   в Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context)\r\n   в Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context)\r\n   в Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden)\r\n   в Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally)\r\n   в Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy)\r\n   в Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)\r\n   в Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)\r\n   в Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context)\r\n   в Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments, IReleasePolicy policy)\r\n   в Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy)\r\n   в Castle.MicroKernel.DefaultKernel.Resolve(Type service, IDictionary arguments)\r\n   в Castle.Windsor.WindsorContainer.Resolve(Type service)\r\n   в Abp.Dependency.IocManager.Resolve(Type type)\r\n   в Abp.Dependency.IocResolverExtensions.ResolveAsDisposable[T](IIocResolver iocResolver, Type type)\r\n   в Abp.WebApi.Controllers.AbpApiControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   в System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   в System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
  "innerException": {
    "message": "An error has occurred.",
    "exceptionMessage": "Can't create component 'DERC.ApplicationServices.DocumentAppService' as it has dependencies to be satisfied.\r\n\r\n'DERC.ApplicationServices.DocumentAppService' is waiting for the following dependencies:\r\n- Service 'Abp.Domain.Repositories.IRepository`1[[DERC.Entities.Document, DERC.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' which was not registered.\r\n",
    "exceptionType": "Castle.MicroKernel.Handlers.HandlerException",
    "stackTrace": "   в Castle.MicroKernel.Handlers.DefaultHandler.AssertNotWaitingForDependency()\r\n   в Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)\r\n   в Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)\r\n   в Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context)\r\n   в Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernelByType(CreationContext context, ComponentModel model, DependencyModel dependency)\r\n   в Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveFromKernel(CreationContext context, ComponentModel model, DependencyModel dependency)\r\n   в Castle.MicroKernel.Resolvers.DefaultDependencyResolver.ResolveCore(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)\r\n   в Castle.MicroKernel.Resolvers.DefaultDependencyResolver.Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)\r\n   в Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateConstructorArguments(ConstructorCandidate constructor, CreationContext context)\r\n   в Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context)\r\n   в Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context)\r\n   в Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden)\r\n   в Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally)\r\n   в Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy)\r\n   в Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)\r\n   в Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)\r\n   в Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context)\r\n   в Castle.Core.InterceptorReference.Castle.MicroKernel.IReference<Castle.DynamicProxy.IInterceptor>.Resolve(IKernel kernel, CreationContext context)\r\n   в Castle.Windsor.Proxy.AbstractProxyFactory.ObtainInterceptors(IKernel kernel, ComponentModel model, CreationContext context)\r\n   в Castle.Windsor.Proxy.DefaultProxyFactory.Create(IKernel kernel, Object target, ComponentModel model, CreationContext context, Object[] constructorArguments)\r\n   в Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext context, ConstructorCandidate constructor, Object[] arguments)"
  }
}

How do I solve this problem?

A: When checking what basic convention registration does you can see:
        //Transient
        context.IocManager.IocContainer.Register(
            Classes.FromAssembly(context.Assembly)
                .IncludeNonPublicTypes()
                .BasedOn<ITransientDependency>()
                .If(type => !type.GetTypeInfo().IsGenericTypeDefinition)
                .WithService.Self()
                .WithService.DefaultInterfaces()
                .LifestyleTransient()
            );

        //Singleton
        context.IocManager.IocContainer.Register(
            Classes.FromAssembly(context.Assembly)
                .IncludeNonPublicTypes()
                .BasedOn<ISingletonDependency>()
                .If(type => !type.GetTypeInfo().IsGenericTypeDefinition)
                .WithService.Self()
                .WithService.DefaultInterfaces()
                .LifestyleSingleton()
            );

        //Windsor Interceptors
        context.IocManager.IocContainer.Register(
            Classes.FromAssembly(context.Assembly)
                .IncludeNonPublicTypes()
                .BasedOn<IInterceptor>()
                .If(type => !type.GetTypeInfo().IsGenericTypeDefinition)
                .WithService.Self()
                .LifestyleTransient()
            );

What means that first you have to mark your dependencies either with ITransientDependency or ISingletonDependency interfaces to be able to register them by conventions. And then anyway generic types are excluded, so you must register them by standard approach:
IocManager.IocContainer.Register(Component.For(typeof(ITest<,>)).ImplementedBy(typeof(Test<,>)));


text:
Q: Is Windows File-Mapping (named) invalidated by file overwrites? We have a data processing engine that uses reference data that is mapped into memory when first opened using CreateFile and CreateFileMapping from the Windows API. This results in the data being cached for each portion of the file that is read, and the cache persists until the system is restarted or needs the memory for something else (even if the application is closed and reopened).  We periodically install updated reference data, and I've been trying to determine if simply overwriting the reference file with a new version will invalidate the cache or if the system must be restarted.
I've tried searching here and elsewhere (including MS documentation) and have yet to find a definitive answer. I hoping someone has some idea. Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Polling for a job status java I'm looking for a way to check a job status over a period of time:
If during the polling I get a result that the job was completed, I return it, otherwise I keep polling until the period I set is over and return a failure result.
I know how to do this using a timer and a while loop.
Is there a better way of doing it?
Thanks in advance

A: Better way to pool for the result should be using CompletionService.
Since you are already using asynchronous way of communication, make your thread implement Callable and implement call method similar to what you would do in a run method.
Now when you use completion service and to your executor service just say submit. With completion Service you get a blocking queue on which as and when you get the result completion service will put the result onto Queue and you can then do whatever you want with the result.


text:
Q: How to compute Wilcoxon rank-sum test in Stata? I would like to compute the Wilcoxon rank-sum test in Stata for two countries of my sample with the dummyvalue 3 and 6.
Can anyone give the right code for Stata?

A: Something like:
. ranksum y if country==3 | country==6, by(country)
or, slightly more concisely,
. ranksum y if inlist(country,3,6), by(country)
 (where y is the outcome variable you wish to test).


text:
Q: Facebook Messenger chat widget not loading
I have whitelisted the domains on our FB page and generated the chat widget. The code did nothing visible on the page (all content blockers disabled).
On our CMS we lack the ability to add code to head/ start or end of body.
I then used the guides from:
https://medium.com/@jamesfuthey/how-to-add-facebook-live-chat-to-your-website-dd48fc8bb066  &&
https://www.labnol.org/internet/embed-facebook-customer-chat-widget/30663/
I.e. creating a developer app and using APP_ID.
This also did not work see: https://www.trentstudents.org/test-fb1
I have also tried manually adding the script to the page in the correct place i.e.
var facebookWidget = `

`;
$('body').prepend(facebookWidget);

Finally I attempted copying and editing the code from https://www.lsu.co.uk/
Sample page here:
https://www.trentstudents.org/test-fb2
Blocked by iframe origin policy (I attempted to mod the code ids and domains to ours - clearly I missed something)

<div class="fb-customerchat fb_invisible_flow fb_iframe_widget" attribution="setup_tool" page_id="127611563950728" logged_in_greeting="Hi! 👋  How can we help you?" logged_out_greeting="Hi! 👋  How can we help you?" fb-xfbml-state="rendered" fb-iframe-plugin-query="app_id=383830712455959&attribution=setup_tool&container_width=0&locale=en_US&logged_in_greeting=Hi!%20%F0%9F%91%8B%20%20How%20can%20we%20help%20you%3F&logged_out_greeting=Hi!%20%F0%9F%91%8B%20%20How%20can%20we%20help%20you%3F&page_id=10144058117&sdk=joey"><iframe name="f105c6e6d6280d4" width="1000px" height="1000px" frameborder="0" allowtransparency="true" allowfullscreen="true" scrolling="no" allow="encrypted-media" title="" src="https://www.facebook.com/v3.2/plugins/customerchat.php?app_id=383830712455959&attribution=setup_tool&channel=https%3A%2F%2Fstaticxx.facebook.com%2Fconnect%2Fxd_arbiter%2Fr%2Fvy-MhgbfL4v.js%3Fversion%3D44%23cb%3Dfac9b0f08f1698%26domain%3Dwww.lsu.co.uk%26origin%3Dhttps%253A%252F%252Fwww.lsu.co.uk%252Ff1f65df83379dd4%26relation%3Dparent.parent&container_width=0&locale=en_US&logged_in_greeting=Hi!%20%F0%9F%91%8B%20%20How%20can%20we%20help%20you%3F&logged_out_greeting=Hi!%20%F0%9F%91%8B%20%20How%20can%20we%20help%20you%3F&page_id=10144058117&sdk=joey" style="border: none; visibility: visible; width: 288pt; height: 214px; border-radius: 9pt; bottom: 63pt; padding: 0px; position: fixed; right: 9pt; top: auto; z-index: 2147483647; max-height: 100%;" class=" fb_customer_chat_bounce_in_v2" data-testid="dialog_iframe">

Finally in trying to go back to the facebook page and generated new code it no longer works.
Video here:
https://tinytake.s3.amazonaws.com/pulse/d-manicx100/attachments/9953495/TinyTake20-02-2019-10-31-20.mp4
Original generated code below (includes custom theme color):

Seen here:
https://www.trentstudents.org/test-fb3

A: The answer was that a css file from an external library was blocking it with
.fb_reset#fb-root {display:none;}

Strangely the official SDK version still didn't work only the one with APP_ID. I also set the version to 4.4 as referenced in the JS file (as of 20th February 2019)
Final working code:


text:
Q: What is the difference between spin_lock and raw_spin_lock()? There is raw variant of each spin lock available in linux kernel, I want to know its usage ? e.g. :
raw_spin_lock(), raw_spin_lock_irqsave(), etc.

A: spin_lock* functions do the same as raw_spin_lock* ones plus, when lock debugging is enabled(CONFIG_DEBUG_LOCK_ALLOC), perform some additional runtime checks for lock operations, such as checks for deadlock. These checks are performed by lockdep subsystem.
As a rule, spin_lock* functions should be used whenever it is possible.
Only in rare cases of very tricky locking policy, when lockdep can produce false warnings, raw_spin_lock* functions can be used.
Also, raw_* functions can be preferred to common ones for reduce memory usage or perfomance reasons. But it should be actual time/space measurements, reflected significant wins from using these optimizations.

A: The main difference is spin_lock variants map to raw_spin_lock variants for non-RT whereas if CONFIG_PREEMPT_RT is set, then they map to rt_spin_lock which can sleep.
By decoupling the spin_lock from sleeping vs non-sleeping variations depending on whether we are RT or not, the spin_lock API can be kept consistent across the kernel code.


text:
Q: Large list with custom permissions Imagine there situations:

*

*List with 6 000 items. The list has broken permission inheritance. Each item has custom permissions set. Only the author of the item has contribute permission level set. The member group has Read permission level set. The owner group has Full control permission level set.

*List with 6 000 items. The list has broken permission inheritance. Each item has custom permissions set. The author of the item and another user have contribute permission level set. The owner group has Full control permission level set. The custom group (Auditors) has Read permission level set.

*List with 60 000 items. The list has broken permission inheritance. Each item has custom permissions set. The author of the item and another user have contribute permission level set. The owner group has Full control permission level set. The custom group (Auditors) has Read permission level set.

Do you see any problems with scenario above?

A: Your design will hit two major limitations which could massively impact performance:

*

*All of your lists have >5.000 items. This is what Microsoft calls a "large list". Study this excellent article and follow it's recommendations. You souldn't blindly increase the "List view Threshold"

*Assigning permissions per item also slows things massively down. I have seen lists&libraries timing out when performing a permission change because of the excessive use of item-level permissions. This article has excellent information in section "Throttling and limits -> Unique permissions". It is written for 2010, but still valid in newer versions.

Whenever permission inheritance is broken for an item, such as a folder, it is counted as a unique permission toward this limit. Each time permissions inheritance is broken, a new scope ID is created. Each time that you query on a view, you join against the scopes table. Then, when a query is performed, each unique access control list (ACL) must be parsed and processed. A large number of unique permissions in a list will adversely affect performance and is not recommended. As the number of unique permissions in a list grows, query performance will degrade. Even though the default limit is 50,000 unique permissions, you might want to consider lowering this limit to 5,000 unique permissions.

A: Sharepoint doesn't like breaking permissions. If the list will not grow above the 6k you are probably fine (I would just increase the list view threshold for that list using PowerShell to 6K - but just for the list not the whole app thorough the Central admin). The more the list grows the more perf problem you will have (you can mitigate them by throwing more resources on the farm and sql server - mainly memory for SQL and fast disks).


text:
Q: where to save activation data of the application? In my application I am gonna use online activation to control piracy.but the problem is that once user activates the software, how do i detect that that application is activated.is there any way to store the data that this application is activated. don't tell me registry because this way is not secure.Any information related to online activation will be helpful to me.i have decided to create file in system drive and my application check for that file every time it starts.If file found then application starts and if it doesn't then it ask for the key. is that secure ?any suggestion will be good!!

A: The issue you mentioned is one you need to consider, but there are many others:

*

*How can users activate licenses on systems that don't have a network connection?

*If you follow the standard practice of node-locking each license (automatically reading some system parameters such as MAC address, host name, hard disk ID etc.) and checking these at run time, how will you accommodate users who upgrade their system and so cause one of these parameters to change?

*What about users who want to relocate their license to a different system, such as moving it from their desktop to the laptop, or to a new system?

*What about users who call you (and they will) and say: "Help, my system has crashed so I need to get my license running on a different machine?"

*If you are using the activation system to set a license time limit, such as 30 days for a trial license or a year for a subscription, how can you protect against users who try to cheat on this by mis-setting their system clock either before they activate their license or after it is activated?

*What if you decide to offer different versions of your application - can your activation system manage this? e.g. enable or configure product features for each user based on their activation license, but all from one executable

*How about reporting on licenses activated - does your server capture the data on licenses activated and provide reports, alert etc.?

*What if someone wants to buy a pool of, say, 20 licenses? Do you have to provide 20 different activation IDs, or can you provide one ID that will allow 20 licenses to be activated?

Just some things to think about based on years of experience in the field.

A: There are two different takes on "securing the activation data" that I can see:
1) If you are trying to secure the activation data from the user, so that the user can not copy the data to a different computer and use the software there as well, I propose the following protocol:
During activation, uniquely identifying features of the user's environment are hashed and sent to the activation server.  The activation server generates an activation that is signed using a secret key.  On product start, your product verifies that the activation was signed by your server (using the server's public key) and that the local environment hashes to the same signed value contained in the activation.  If it fails, then the environment has either changed (new installation of the operating system?) or the data has migrated to a new environment requiring (by the sounds of it) a new license / activation.  Either way, the user requires a new activation.
2) If you're trying to protect the activation data from corruption then consider supplementing the former protocol with logic that, if the customer tries to re-activate with the same UID, allow the activation to go through again, which should result in an identical activation instance being sent back to the customer.
These are off the cuff, I don't guarantee either of these to be bulletproof.  Also, remember, a pirate only has to bypass verification for activation to be a moot point.
Also, I feel it's important to note that, with this scheme the idea is that you don't have to hide activation information anywhere.  You can store it wherever is convenient.


text:
Q: Is it possible to modify the position of items in a LazyVGrid/LazyHGrid (SwiftUI 5.5)? I'm relatively new to Swift and have a grid layout question: I'm currently using a LazyHGrid with adaptive grid items and a single column to flexibly layout items without a predetermined column count. I determine the number of columns shown by setting a maxWidth the grid layout with a maxWidth based on the number of items to be displayed
What I'm trying to accomplish in each of the scenarios below (with a solution that would scale up too) is essentially to adjust the positions in the examples below by shifting items out of position "" and into position "⚪", eliminating the "floating orphan" item not hugging the edge. The "⚫" positions are already correct.
CONSTRAINTS

*

*I want to minimize the width that this grid uses, but not all rows can accommodate the taller stacks (so setting a bunch of brittle rules seems like a poor solution) and I'm not interested in setting a fixed row item height to remove the need for a dynamic solution

*I'd like to avoid creating grid manually with nested HStacks and VStacks and writing a bunch of extra logic to manage the contents of each row and column given the height of the parent row (as retrieved via GeometryReader).

WHAT I'VE TRIED

*

*I looked in the Lazy_Grid docs to see if there was a view modifier that would accomplish this -- didn't come across one (though it's entirely possible I've missed it!)

*I thought maybe flipping the layoutDirection (from LTR to RTL) might do it, but no such luck

*I shifted around the alignment values of the repeated gridItem and lazyHGrid container, but the floating orphan remained

EXAMPLES

*

*For three items:

/* short */
___________
      ⚫⚫|
      ⚪|

/* tall */
___________
        ⚫|
        ⚫|
        ⚫|

*

*For four items:

/* short */
___________
      ⚫⚫|
      ⚫⚫|

/* tall */
___________    ___________
      ⚫⚫|          ⚫⚫| // NOTE: I *could* constrain the height in this case
      ⚪|          ⚫⚫| // to achieve the 2x2 grid but would rather not
      ⚪|

*

*For five items:

/* short */
___________
    ⚫⚫⚫|
    ⚫⚪|

/* tall */
___________
      ⚫⚫|
      ⚫⚫|
      ⚪|

*

*For six items:

/* short */
___________
    ⚫⚫⚫|
    ⚫⚫⚫|

/* tall */
___________
      ⚫⚫|
      ⚫⚫|
      ⚫⚫|

*

*For seven items:

/* short */
___________
  ⚫⚫⚫⚫|
  ⚫⚫⚪|

/* tall */
___________
      ⚫⚫|
      ⚫⚫|
      ⚫⚫|
      ⚪|

let items = filterItems()
let iconCount = CGFloat(items.count)
let iconSize: CGFloat = 18
let spacing: CGFloat = 2

// NOTE: `iconCount / 2` because the min-height of the parent
// only fits two items. The current item count is 7 and it's
// unlikely that it'd ever do more than double.

let cols = CGFloat(iconCount / 2).rounded(.up)
let maxWidth = calcWidth(for: cols, iconSize: iconSize, spacing: spacing)
let minWidth = cols < 2 ? maxWidth : calcWidth(for: cols - 1, iconSize: iconSize, spacing: spacing)

LazyHGrid(
  rows: Array(
    repeating: GridItem(
      .adaptive(minimum: iconSize, maximum: iconSize),
      spacing: spacing,
      alignment: .center
    ),
    count: 1
  ),
  alignment: .center,
  spacing: spacing
) {
  ForEach(0..<items.count, id: \.self) { n in

    ...item views...

  }
}
.frame(minWidth: minWidth, maxWidth: maxWidth)

My brain is stuck on finding a Swift concept similar to CSS's FlexBox justify-content: flex-end; align-items: flex-start but it feels to me there should be a more Flexy/Swifty solution for this that I'm just missing?
(The grid is nested within an HStack currently, and shoved to the top-trailing corner of it's parent with a spacer, effectively accomplishing the align-items: flex-start portion of the Flexbox solution mentioned above asd as shown in the illustrations above)

A: Edit: Layout direction works for me
You mentioned this didn't work in your post, but I just tested setting layout direction to right-to-left, and it works. All the end items are aligned to the right. Maybe the specific OS you're testing on has a layout bug. The full playground snippet (tested on Xcode 13):
import UIKit
import PlaygroundSupport
import SwiftUI
import Foundation

let iconCount: CGFloat = 4
let iconSize: CGFloat = 18
let spacing: CGFloat = 2
let cols: CGFloat = 2
let maxWidth = calcWidth(for: cols, iconSize: iconSize, spacing: spacing)
let minWidth = cols < 2 ? maxWidth : calcWidth(for: cols - 1, iconSize: iconSize, spacing: spacing)

func calcWidth(for cols: CGFloat, iconSize: CGFloat, spacing: CGFloat) -> CGFloat {
    return iconSize * cols + spacing * cols
}

PlaygroundPage.current.liveView = UIHostingController(rootView: {
    TabView {
        HStack {
            LazyHGrid(
              rows: Array(
                repeating: GridItem(
                  .adaptive(minimum: iconSize, maximum: iconSize),
                  spacing: spacing,
                  alignment: .center
                ),
                count: 1
              ),
              alignment: .center,
              spacing: spacing
            ) {
              ForEach(0..<Int(iconCount), id: \.self) { n in
                  Text("B")
                      .frame(width: iconSize, height: iconSize)
                      .border(.red)
              }
            }
            .frame(minWidth: minWidth, maxWidth: maxWidth)
            .background(Color.green)
            .frame(height: iconSize * 3 + spacing * 2)
            .environment(\.layoutDirection, .rightToLeft)
            // I also tried this, but it isn't needed
            //.flipsForRightToLeftLayoutDirection(true)
        }
    }
}())

Original answer:
This is not the ideal solution, but one option is to use 3D rotation to flip the layout on the Y axis. I used a simple text view in Playgrounds as an example:
LazyHGrid(
  rows: Array(
    repeating: GridItem(
      .adaptive(minimum: iconSize, maximum: iconSize),
      spacing: spacing,
      alignment: .center
    ),
    count: 1
  ),
  alignment: .center,
  spacing: spacing
) {
  ForEach(0..<Int(iconCount), id: \.self) { n in
      Text("B")
          .frame(width: iconSize, height: iconSize)
          .rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))
  }
}
.frame(minWidth: minWidth, maxWidth: maxWidth)
.rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))


text:
Q: How to Show Message Box for specific User I am trying to solve an issue with showing Message Boxes/Alerts for a specific User. My application starts with Windows and it interacts with multiple Windows users for the whole time(1 or more users can be logged in the same time). When the user logs in and performs certain operations, app should display Message Box/Alert Dialog for this user only. My question is: how to display/show dialog for this user only?

A: I think you can get the current username to check if it's the username you want to Show the message box accordingly:
//..............
if(Environment.UserName == "yourUserName"){
   //Show message box here
}
//..............


text:
Q: Checking for equality in Objective-C How do i check the key in dictionary is same as the string in method parameter?
i.e in below code , dictobj is NSMutableDictionary's object , and for each key in dictobj i need to compare with string. How to achieve this ? Should i typecase key to NSString??
-(void)CheckKeyWithString:(NSString *)string
{
   //foreach key in NSMutableDictionary
   for(id key in dictobj)
     {
       //Check if key is equal to string
       if(key == string)// this is wrong since key is of type id and string is of NSString,Control doesn't come into this line
          {
           //do some operation
          }
     }
}

A: When you use the == operator, you are comparing pointer values. This will only work when the objects you are comparing are exactly the same object, at the same memory address. For example, this code will return These objects are different because although the strings are the same, they are stored at different locations in memory:
NSString* foo = @"Foo";
NSString* bar = [NSString stringWithFormat:@"%@",foo];
if(foo == bar)
    NSLog(@"These objects are the same");
else
    NSLog(@"These objects are different");

When you compare strings, you usually want to compare the textual content of the strings rather than their pointers, so you should the -isEqualToString: method of NSString. This code will return These strings are the same because it compares the value of the string objects rather than their pointer values:
NSString* foo = @"Foo";
NSString* bar = [NSString stringWithFormat:@"%@",foo];
if([foo isEqualToString:bar])
    NSLog(@"These strings are the same");
else
    NSLog(@"These string are different");

To compare arbitrary Objective-C objects you should use the more general isEqual: method of NSObject. -isEqualToString: is an optimized version of -isEqual: that you should use when you know both objects are NSString objects.
- (void)CheckKeyWithString:(NSString *)string
{
   //foreach key in NSMutableDictionary
   for(id key in dictobj)
     {
       //Check if key is equal to string
       if([key isEqual:string])
          {
           //do some operation
          }
     }
}


text:
Q: c++ forward declaration #include <iostream>
#include <cstring>
using namespace std;

class Obj;

class Test {
    friend class Obj;
public:
    Test()
    {

    }
    ~Test()
    {

    }
    void foo()
    {
        //print();
            //Obj::print();
            //Obj x;
            //x.print();
    }
};

class Obj {
public:
    void print()
    {
        cout << "print here" << endl;
    }
};

int main()
{
    Test test;
    test.foo();
    return 0;
}

Quick question,how can I call print the correct way in Test::foo() ?

A: You need to define the member function after the definition of Obj:
class Test {
public:
    void foo();
};

class Obj {
public:
    void print() { }
};

void Test::foo() {
    Obj o;
    o.print();
}

A: As mentioned by james you should define the member function after the definition of Obj. Also you are calling Obj::print, but print is not a static member function so you must call it on an instance of Obj not Obj itself.
If you really do want print to be a static member, declare it so.
class Obj {
public:
    static void print(){ blah }
}

Also you do not need to make Obj a friend in order to access its public methods.
Also can OP please define "correct way", I was assuming you wanted it to be a static member function, james' answer is correct if you want one instance of Obj per instance of Test.
UPDATED
OP, as per your comment you must have the declaration of Obj along with print BEFORE using it within Test. This can be achieved in many ways:

*

*move the entire class Obj defintion (and declaration) before Test

*declare Obj's methods with its class definition and define them later.

*declare Test like you have and Define Test as per James' post (after Obj).

The following works fine:
#include <iostream>
#include <cstring>
using namespace std;

class Obj {
public:
    static void print()
    {
        cout << "print here" << endl;
    }
};

class Test {
public:
    Test()
    {

    }
    ~Test()
    {

    }
    void foo()
    {
            Obj::print();
    }
};

int main()
{
    Test test;
    test.foo();
    return 0;
}

However it is always nicer (in my opinion) to separate declaration from definition for all but the most trivial of cases.


text:
Q: Zend Framework Model is it posible to have a true Model Layer in PHP like in Ruby on Rails? With Zend Framework you can create a Model but this is a class. As I know you have to write all the logic by myself.
Solutions?

A: True, in Zend Framework you need to declare classes for the database tables you'd like to access. But the rest can be done implicitly, if the default behavious is sufficient. The following is a valid and functional model class (compare to http://framework.zend.com/manual/en/zend.db.table.html#zend.db.table.introduction):
class bugs extends Zend_Db_Table_Abstract
{
    // table name matches class name
}

This should let you access the table named "bugs", e.g.:
$table = new bugs();
$data = array(
    'created_on'      => '2007-03-22',
    'bug_description' => 'Something wrong',
    'bug_status'      => 'NEW'
);
$table->insert($data);

Again, the example was taken directly from the documentation mentioned above.

A: Or since 1.8.x there is a DataMapper pattern used for models (see quickstart in manual)

A: i wrote a script that might suite your needs.
http://code.google.com/p/zend-db-model-generator/


text:
Q: Qt 5.15.2 QVector::rend and QVector::end problem I am learning QVector class and i try QVector::rbegin,begin,end and rend. rbegin and begin work correctly but the others don't. First i think push_back may cause and i change it to append but it has still same problem. I explain as a comment near the code.
#include <QDebug>
#include<QString>
#include<iostream>
#include<QVector>

int main(){

    QVector<int> vect;
    for(int i = 0; i<=50;i+=10)
        vect.push_back(i);

    for(int x:vect)
        std::cout<<x<<" ";
    std::cout<<std::endl;

    std::cout<<"rbegin: "<<*vect.rbegin()<<std::endl; //it works correctly
    std::cout<<"end: "<<*vect.end()<<std::endl; // it turns different numbers, 15794368, 16777408...
    std::cout<<"rend: "<<*vect.rend()<<std::endl; //it always turns 16, i don't know where is 16 or what i miss
    std::cout<<"begin: "<<*vect.begin()<<std::endl; //it works correctly

   return 0;
}

One of the results of the program is:
0 10 20 30 40 50
rbegin: 50
end: 16777408
rend: 16
begin: 0 ```


text:
Q: Host Angular application on raspberry pi using nginx, socket.io and nodejs I can't find a configuration to make this work. I want to host an angular app (a board game) and a nodejs server (which communicates with the board game) on a raspberry pi via nginx (also already tried apache).
I start to get the feeling it's not a problem with the nginx configuration, but something fundamental I am missing.
Working:

*

*Running the Angular app (via ng serve) and the nodejs server (via
ts-node ./src/app.ts) locally

*Running the Angular app (via ng serve) local and the nodejs server on the raspberry

Not working

*

*hosting angular app via nginx (putting the content of dist folder (generated by ng build --prod) into var/www/html) and running nodejs server on raspberry  --> resulting in Error during WebSocket handshake: Unexpected response code: 400
Code
Nodejs Server
const Express = require('express')();
const Http = require('http').Server(Express);
const Socketio = require('socket.io')(Http);

Http.listen(3333, () => {
  console.log('Listening at :3333...');
});

Angular App Client
import { SocketIoConfig, SocketIoModule } from 'ngx-socket-io';

const config: SocketIoConfig = { url: 'http://192.xxx.xxx.xx:3333', options: { transports: ['websocket'] } };

@NgModule({
  imports: [CommonModule, SocketIoModule.forRoot(config)],
  exports: [SocketIoModule]
})
export class DataAccessModule {}

nginx config
    server {
        location ~* \.io {
            proxy_pass http://localhost:3333;
            proxy_redirect off;

            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            add_header X-location contains-io always;
        }
    }

EDIT: If I remove my nginx config additions I get the same results. Is there a way to test if the config is used?
Some other weird thing I discovered is, that I only see a blank page and not a single console.log when running the angular app via ng serve on the raspberry and go to localhost:4200

A: You better use ng build instead of ng serve, and direct your Nginx to your dest folder, like this:
    location / {
            root   /var/www/angular-deploy; // move your dest into here
            index  index.html index.htm;
        }

You can read this for more details, hope it will help

A: Turns out the only thing I needed was a dyndns, instead of localhost or a static ip.
So the client code looks like this:
  private socketUrl = 'http://example.ddns.net';
 // also switched to the plain socket.io-client package instead of ngx-socket-io, but I don't think this is necessary
  socket: SocketIOClient.Socket = io(this.socketUrl);

and the nginx conf:
    server {
        listen 80;
        server_name example.ddns.net;
        root /var/www/app;

        location ^~ /socket.io/ {
            proxy_pass http://127.0.0.1:3333;
            proxy_redirect off;

            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }

        location / {
            try_files $uri $uri/ /index.html;
            proxy_set_header   X-Forwarded-For $remote_addr;
            proxy_set_header   Host $http_host;
            index  index.html index.htm;
        }
    }


text:
Q: Algebra rearrangement, solve for x How do I solve this equation for x?
$$1.43 = \frac{x}{0.99x+5.21\times10^{-5}}$$
I have tried rearranging it, but can't seem to get a positive number.

A: Let $A = 1.43, B=0.99, C = 5.21 \times 10^{-5}$
The equation is $A = \frac{x}{Bx + C}$
Rearranging,
$ABx + AC = x$
$x(AB-1) = -AC$
$x = \frac{AC}{1-AB}$
which evaluates to approximately $x = -1.792 \times 10^{-4}$, indeed a negative real number.


text:
Q: Is there a way to control both Order By and Order query parameters from one input field I want to give the user the ability to order posts by post date/alphabetically either on ASC or DESC order through a select input on an archive page.
The easy way would be to show two inputs on the front end: one controlling the order_by parameter, and other controlling the order parameter.
But it would be a lot better if it were just one select input field with four options:

*

*Latest

*Oldest

*Alphabetical A-Z

*Alphabetical Z-A

I tried cheating, using & inside each option's value, but it gets automatically escaped on the URL.
<form action="">
    <select name="orderby" id="">
        <option value="post_date&order=DESC">Latest</option>
        <option value="post_date&order=ASC">Oldest</option>
        <option value="post_title&order=ASC">Alphabetical A-Z</option>
        <option value="post_title&order=DESC">Alphabetical A-Z</option>
    </select>
    <button>Filter</button>
</form>

This code gives me a URL like this: http://example.com/?orderby=post_date%26order%3DASC
I could do it easily with javascript, or with PHP, but I wanted to know if there was a better solution.

A: There are many ways you could proceed. Here is one.
I would defined the four options like this:
function fetch_order_from_form( $query ){
    if( $query->is_page( ThePAGEID ) && $query->is_main_query() && (isset($_POST["orderby"]) && !empty($_POST["orderby"])) ) {
        if( $_POST["orderby"]) == 1){
            $query->set( 'orderby', 'date' );
            $query->set( 'order', 'ASC' );
        }
        elseif( $_POST["orderby"]) ==2 ){
            $query->set( 'orderby', 'date' );
            $query->set( 'order', 'DESC' );
        }
        elseif( $_POST["orderby"]) ==2 ){
            $query->set( 'orderby', 'title' );
            $query->set( 'order', 'ASC' );
        }
        elseif( $_POST["orderby"]) ==2 ){
            $query->set( 'orderby', 'title' );
            $query->set( 'order', 'DESC' );
        }
    }
}
add_action( 'pre_get_posts', 'fetch_order_from_form' );

A: If you only need to use URL query parameters, you should use simple links instead of form.
If you want to use form, but still want to use URL query parameters, you should definitely go with javascript.
But, if you really want to use form and $_POST data, you can use this:
$orderby = isset($_POST['orderby']) ? $_POST['orderby'] : null;

switch ($orderby) {
    case 'a_to_z':
        $field = 'post_title';
        $sort = 'ASC';
    break;
    case 'z_to_a':
        $field = 'post_title';
         $sort = 'ASC';
    break;
    case 'date_oldest':
        $field = 'post_date';
         $sort = 'ASC';
    break;
    default:
         $field = 'post_date';
        $sort = 'DESC';
    break;
}


text:
Q: attempting to create masonry grid with material design lite cards so i'm making an app that has various material design lite cards with images, such that the cards are in a masonry grid. i'm using the masonry module (https://masonry.desandro.com/) to attempt to create a grid in conjunction with mdl-grid, but extra whitespace is being added to the end of each card, like this
how do i make it such that the masonry grid is, well, an actual masonry grid? i want to be able to remove this bottom space and place the card under the last one without accounting for the height in other cards in that row.
my full project is available at https://github.com/ix/bunnydb, but the relevant portions are here, in ejs and css:
(portions of) index.ejs (loaded by express)

  <% files.forEach((bun) => { %>

        <img src=<%= bun.path.replace("public/", "") %> alt="" />

<%= bun.originalname %>

        <a class="mdl-button mdl-button--accent mdl-js-button-mdl-js-ripple-effect" href=<%= bun.path.replace("public/", "") %>>
          View

  <% }); %>

index.css
.masonry-grid {
    max-width: auto;
}

.masonry-grid:after {
    content: '';
    display: block;
    clear: both;
}

.masonry-grid-item {
    /* width: 160px;
    height: 120px; */
    float: left;
}

.mdl-card {
    height: auto;
}

.mdl-card__media {
    margin: 0;
}

.mdl-card__media > img {
    width: 100%;
    height: auto;
}


text: Q: Varieties receiving a morphism from projective space. Are any interesting family of smooth projective varieties that receive a surjective regular morphism (and maybe finite) from projective space? Now what we replace projective space by varieties constructed out of projective spaces, like product of projective space or projective bundles over projective spaces ...


text:
Q: How can I "undo" a multi-child deletion? In this portion of code I delete a selection of items from my Firebase Realtime Database:
for (Expense i : selectedExpenses) {

    final Expense expenseBackUp = new Expense(i.getItem(), i.getCategory(), i.getDate(), i.getId(), i.getAmount());

    databaseReference.child(i.getId()).removeValue().addOnCompleteListener(task -> {

        if (task.isSuccessful()) {
            Snackbar.make(activity.findViewById(android.R.id.content), activity.getString(R.string.deleted_alert),
                    Snackbar.LENGTH_LONG).
                    setAction(R.string.undo, view1 -> databaseReference.child(i.getId()).setValue(expenseBackUp)).show();
        } else {
            Toast.makeText(activity.getApplicationContext(), activity.getString(R.string.input_error) + task.getException(), Toast.LENGTH_SHORT).show();
        }
    });
}

Now I want to implement an undo button within a Snackbar.
I get to show the Snackbar with the undo button, but I need some help with the expenseBackUp because it only retrieves my last deleted item, which works fine when a user deletes only 1 item.
How can I go around this, so I can get every deleted item back if undo button is hit?

A: You can delete the items in two phases: first, you mark the 'deleted' items in the database as deleted with an extra boolean field 'deleted' in the table. Then on undo click, you can easily undo the delete.
If the user does not click the undo, you can fully delete the marked items after the snackbar timeout.

A: Adding a flag to each object will work but it also has a downside. If you want to query all items of a node where the property "deleted" holds the value of true, it will solve the problem, but if you need to add another filter, it will not work, because the Firebase Realtime Database does not support queries on multiple properties.
To solve this, you can perform the delete operation, and if the user clicks on the "UNDO" button in Snackbar, write the data back. It's not the best solution, as it implies a delete operation followed by a write operation but it will do the trick.
Another option that you have, would be to simulate the delete operation. How? When the user clicks on the delete button, don't perform the actual delete operation. Wait to see if the user clicks "UNDO". If the user clicks "UNDO" take no action, otherwise, delete the elements.
To be able to update/delete multiple elements, please check my answer from the following post:

*

*Edit specific values in Firebase database using Android Studio


text:
Q: Shorten Apple Maps Location Share Link in iOS I have a direct chat messaging app where when a user pastes and submits a share link via apple maps of a specific location, it displays as a long ugly link. The redirect and it being clickable is all good and okay, but optically, it'd be nice to abbreviate it like iMessage does for apple maps links to maps.apple.com.
Is there any way to detect and convert the link into one that is easier to consume? I could not find any references or threads to even begin experimenting with solutions, so any thoughts would be greatly appreciated.

A: You can use Apple's CLGeocoder to convert coordinates and create a "link preview" feature inside your app. Here are some useful links:
https://developer.apple.com/documentation/corelocation/clgeocoder
https://developer.apple.com/library/archive/technotes/tn2444/_index.html


text:
Q: Multiple UIPickerView on UITableView How can I add multiple UIPickerViews and textfields inside UITableview , and use the different methods for managing UIPickerViews?

A: If you need to show pickerView when textField is selected you need to add the pickerView as inputView to the textField.
If you have many textFields, it would be better to add it when the editing starts for a textField. To identify which textField should be shown picker give tag to each textField.
- (void)textFieldDidBeginEditing:(UITextField *)textField{

   NSInteger tag = textField.tag;

   //Conditionally check which textField you want to show picker
   //Then call the method to add inputView to textField
   [self addInputViewToTextField:textField];

}

- (void)addInputViewToTextField:(UITextField *)textField{

    //Initialize pickerView
    UIDatePicker *datePicker = ...

    textField.inputView = datePicker;

}

A sample project to show UIDatePicker when textField is selected.


text:
Q: Should I use dataTable or panelGrid? JSF

            Emp No
            title
            Name
            shift

        Yeh aik arzi tehreer hai

When I started to convert this code for my JSF app I found that I can use either <h:dataTable> or <h:panelGrid> because both are use here as an alternative of table in html.So first thing which I want to ask is what should I use here?
2ndly how can I handle
 ,
 and
as I didn't find their alternate in JSF.So please can anyone put some effort to help me for thisThanks

A: <h:dataTable> is a good choice if you have (in your backing bean) a set of objects you need to display. For example if you have a List of object Employee (with Id, Name, Surname, etc.) then  is the best choice.
Here you can find an example of how to use dataTable.
<h:panelGrid> is a good choice if you have layout various elements in an certain way. One case, is when you have to split the space in two columns of 80% and 20% respectively.
Though, 'I' suggest to use  (panelGroup) for this purpose see http://www.w3.org/2002/03/csslayout-howto
Edit: With the <h:dataTable> For the header, footer, etc. you have to use the tag <f:facet />
see Multiple Footer Rows in a JSF dataTable


text:
Q: Pyside - Select all text when QLineEdit gets focus I am new to Qt/PySide. I want QLineEdit to select all text in it when it gets focus. After getting focus and selecting all text, it should select all text only after focus is lost and gained again. It should not select all text when I change cursor position after QLineEdit gains focus. How do I do that?
Update: My current code improved as suggested by Ashwani Kumar. I still can't get it to work though:
import sys
from PySide.QtGui import QLineEdit, QApplication, QVBoxLayout, QWidget
class MyLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)

    def focusInEvent(self, e):
        self.selectAll()

app = QApplication(sys.argv)
top = QWidget()
layout = QVBoxLayout()
layout.addWidget(MyLineEdit())
layout.addWidget(MyLineEdit())
top.setLayout(layout)
top.show()
app.exec_()

A: With focusInEvent, when you click the widget, it gets executed, but since you click, it removes the selected text.
To overcome this, we must use the mousePressEvent, this can be done two ways:
import sys
from PySide.QtGui import QLineEdit, QApplication, QVBoxLayout, QWidget
class MyLineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(MyLineEdit, self).__init__(parent)

    def mousePressEvent(self, e):
        self.selectAll()

app = QApplication(sys.argv)
top = QWidget()
layout = QVBoxLayout()
layout.addWidget(MyLineEdit())
layout.addWidget(MyLineEdit())
top.setLayout(layout)
top.show()
app.exec_()

Or you can do it by simply overriding the base QLineEdit class:
txt_demo = QtGui.QLineEdit()
txt_demo.mousePressEvent = lambda _ : txt_demo.selectAll()

However, since we are modifying the mousePressEvent, whenever you try to click text, it will always select all first.

A: For future visitors, I am posting code that is working for me. As I am a newbie I am not sure if the code contains any malpractices. If it does feel free to comment and I'll update my code/answer. Code:
import sys
from PySide.QtGui import QLineEdit, QApplication, QVBoxLayout, QWidget

class LineEdit(QLineEdit):
    def __init__(self, parent=None):
        super(LineEdit, self).__init__(parent)
        self.readyToEdit = True

    def mousePressEvent(self, e, Parent=None):
        super(LineEdit, self).mousePressEvent(e) #required to deselect on 2e click
        if self.readyToEdit:
            self.selectAll()
            self.readyToEdit = False

    def focusOutEvent(self, e):
        super(LineEdit, self).focusOutEvent(e) #required to remove cursor on focusOut
        self.deselect()
        self.readyToEdit = True

app = QApplication(sys.argv)
top = QWidget()
layout = QVBoxLayout()
layout.addWidget(LineEdit())
layout.addWidget(LineEdit())
top.setLayout(layout)
top.show()
app.exec_()

A: You have to subclass the QLineEdit and then use the new class instead of QLineEdit.
e.g: -
class MyLineEdit(QtGui.QLineEdit):
    def __init__(self, parent=None)
        super(MyLineEdit, self).__init__(parent)

    def focusInEvent(self, e):
        self.selectAll()

lineedit = MyLineEdit()

A: QTimer solution as seen on QtCentre:
import types
from PyQt4 import QtCore

def bind(func, to):
    "Bind function to instance, unbind if needed"
    return types.MethodType(func.__func__ if hasattr(func, "__self__") else func, to)

...
self.txtSrc.focusInEvent = bind(lambda w, e: QtCore.QTimer.singleShot(0, w.selectAll), self.txtSrc)

Also the provided solution doesn't require to subclass QLineEdit.

A: These answers don't really provide the sort of standard ergonomics you'd probably want (and users might expect). For example, if you single-click once on a QLE which is not currently all-selected, and then single-click again, typically you'd want the first click to select-all, and the second click to allow you to place the cursor in the specific spot you have chosen.
This can be achieved simply by doing this:
def mousePressEvent(self, event):
    already_select_all = self.text() == self.selectedText()
    super().mousePressEvent(event)
    if not already_select_all:
        self.selectAll()

The question in fact asks about gaining focus, not specifically by mouse-clicking, and indeed, if you are a keyboardist or generally musophobic you'll probably also want the whole text to be selected any time the QLE gains focus, e.g. by tabbing or by use of a QLabel "buddy" mnemonic. This seems to do the job:
class MyLineEdit(QtWidgets.QLineEdit):
    def __init__(self, *args):
        super().__init__(*args)
        self.focus_in_reason = None

    def focusInEvent(self, event):
        super().focusInEvent(event)
        self.selectAll()
        self.focus_in_reason = event.reason()

    def mousePressEvent(self, event):
        super().mousePressEvent(event)
        if self.focus_in_reason == QtCore.Qt.MouseFocusReason:
            self.selectAll()
            self.focus_in_reason = None


text:
Q: Increase size of embedded image in HTML I have an HTML page. There is a base64 encoded image in it. I am planning on writing a javascript to increase the size of the image and content on the page. So everything on the page will appear bigger. I am able to increase the font size but not sure about the embedded image.

A: If you have
<img id="myImage" src="" />

Then you can do it like this:
$('#myImage').attr({
    width: 150,     // new width
    height: 150     // new height
});

A: Well, you can just adjust the css for that image or the attributes. Use either height or width, just not both so they scale properly.
Jquery:
$("img").css("width","150px");

I may be confused but don't all modern browsers support Ctrl + scroll to zoom?

A: With images referenced by URL, you can change height and width (either the HTML attributes or CSS styles) and the browser will resize the image.  I imagine it will work the same with an embedded image.

A: This functionality is available in most modern browsers, and as such it is unnecessary to duplicate it using client-side scripts. Consider simply informing the user that most browsers have text size controls built in (so that they may use this tool on other sites as well).


text:
Q: How else can I map decimals to doubles with EntityFramework POCOs? I'm trying to refactor an an existing codebase to use POCO EF. Currently it uses EntityObjects but there is custom code to "flatten" the mapped objects to POCOs, i.e. for all mapped classes there are currently two related objects, one POCO called MyClass and one EntityObject called MyClassEF which has a single additional method with the signature MyClass Flatten(). This seems horrible, I know, but it has allowed a fairly straightforward mapping of what are decimal types in the database to double types in the model, because the conversion can take place in the Flatten() method.
Double types are used in code because they are considerably faster when performing analytical calculations, decimal types are probably used in the database because they seemed like a good idea at the time and the previous hand-rolled ORM didn't have the type-mapping restrictions that EF does. Unfortunately, simply changing the datatype in the database is now impractical because there are so many applications which use it (although most of them still convert the type to double, they still expect it to be decimal in the db).
So, currently I'm looking at modifying my model classes to have something like this :
private double _myDouble;
public double MyDouble { get { return _myDouble; } set { _myDouble = value; }
public decimal MyDouble_asDecimal {
  get { return Convert.ToDecimal(_myDouble); }
  set { _myDouble = Convert.ToDouble(value); }
}

...which seems fairly unpleasant. Am I missing a blindingly obvious better way to do this?

A: What about a simple extension method(s):
public static class MyExtension
{
    public static decimal ToDecimal(this double d)
    {
        return Convert.ToDecimal(d);
    }

    public static double ToDouble(this decimal d)
    {
        return Convert.ToDouble(d);
    }
}

So your models would remain unchanged and your flatten method just use customer.DoubleValueProperty.ToDecimal();
Not sure if this is what you want :-)
Also, if you are using mapping and flattening, I'd recommend having a look at automapper.  Takes a lot of pain away.


text:
Q: Determine all local maximas and minimas The function is: $f(x,y)=x^2y^2, (x,y) \in \mathbb{R^2}$
$\partial_xf(x,y)=2xy^2$
$\partial_yf(x,y)=2x^2y$
$\partial_{xx}f(x,y)=2y^2$
$\partial_{yy}f(x,y)=2x^2$
$\partial_{xy}f(x,y)=4xy$
so we now that
$2xy^2=0$ and the solution of this equation is that $x = 0$ and $y$ is arbitrary
$2yx^2=0$ and the solution of this equation is that $x$ is arbitrary and $y = 0$
and we get that:
$D^2f(x,0) =\begin{pmatrix}
0 & 0 \\
0 & 2x^2
\end{pmatrix}$ which is positive semidefinit
$D^2f(0,y) =\begin{pmatrix}
2y^2 & 0 \\
0 & 0
\end{pmatrix}$ which is positive semidefinit
What can I say at this point of the Hessian matrix? Or how can I find the extrema of the function?
Thank you in advance.

A: The function $f(x,y)$ is always positive because it is the square of a number -- unless one of $x$ or $y$ is equal to zero.  Therefore, the global minimum is at $f = 0$.  Because the function is smooth, any local max or min must occur when both $f_x = 0$ and $f_y = 0$.  Again, this only happens when one of $x$ or $y$ is zero.  But we already found this to be the global minimum.  Hence, the function has uncountable global minima, which are the lines $x = 0$ and $y = 0$.  The global minima are equivalent to local minima for this function because they all occur at critical points.


text:
Q: Question about the section Hello currently I am having trouble with section.
This is the code and when I run it in the second page it shows 1 Test but since it is section I am expecting to get 1.1 Test which I am not.
\documentclass{report}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{float}
\usepackage{amsmath}
\usepackage[a4paper,margin=1in,footskip=0.25in]{geometry}
\usepackage{graphicx}
\usepackage{tcolorbox}
\usepackage[parfill]{parskip}
\usepackage{mdframed}
\usepackage{eso-pic,xcolor}
\tcbuselibrary{breakable}
\usepackage{tocloft}
\usepackage{fancyhdr}
\usepackage{scrextend}

\colorlet{mygray}{black!30}
\colorlet{mygreen}{green!60!blue}
\colorlet{mymauve}{red!60!blue}

\newcommand*\tocsection[2]{%
  \stepcounter{section}%
  \contentsline{section}{\numberline{\thesection}#1}{#2}%
}
\newcommand*\tocsubsection[2]{%
  \stepcounter{subsection}%
  \contentsline{subsection}{\numberline{\thesubsection}#1}{#2}%
}

\parindent 0pt

\begin{document}

\newpage
\huge
\cleardoublepage
\pagenumbering{roman}
\setlength\parindent{0pt}
Table of Contents\\
\normalsize

\renewcommand{\thesection}{\arabic{section}}
\renewcommand{\thesubsection}{\thesection.\arabic{subsection}}
\large
\renewcommand{\thesection}{\Roman{section}}
\renewcommand{\thesection}{\arabic{section}}
\setcounter{section}{0}
\tocsection{test2}{1}
\tocsubsection{First subsection}{1}
\tocsubsection{Second subsection}{3}
\tocsubsection{Third subsection}{3}

\setlength\parindent{24pt}

\newpage
\pagenumbering{arabic}

\chapter{Test}

\large

\section{Test}
\hspace{20pt} TEST

\end{document}

How can I fix this?

A: Use \renewcommand{\thesection}{\thechapter.\arabic{section}} (in the preamble)

....
\renewcommand{\thesection}{\thechapter.\arabic{section}} % changed <<<<<<<<<<<<<<
\renewcommand{\thesubsection}{\thesection.\arabic{subsection}}

\begin{document}

%   \newpage
    \huge
%   \cleardoublepage
    \pagenumbering{roman}
    \setlength\parindent{0pt}
    Table of Contents\\
    \normalsize
    ....


text:
Q: bootstrap-vue Custom data rendering sorting by item key (simpler than formatter) Using https://bootstrap-vue.org/docs/components/table#custom-data-rendering
would like to enable sorting on some columns, eg by "First name and age"
Docs say it's not possible to sort by custom rendered data, which is ok. For the "First name and age" column, I'd like to specify sortKey to be age field, which exists in items.
{ key: 'nameage', label: 'First name and age', sortable: true, sortKey: 'age' }

However, setting sortKey has no effect. Could this be accomplished, without using a custom formatter and sort/compare function?
Full code:
<template>

      <template #cell(index)="data">
        {{ data.index + 1 }}
      </template>

      <template #cell(name)="data">
        {{ data.value.last.toUpperCase() }}, {{ data.value.first }}
      </template>

      <template #cell(nameage)="data">
        {{ data.item.name.first }} is {{ data.item.age }} years old
      </template>

      <template #cell()="data">
        {{ data.value }}
      </template>

</template>


text:
Q: Game over on Snake Game I'm doing a snake game and I want to display a game over when the spaceship crashes. I want that the Game Over image appears and does something like floating on the center of the boardgame.
I think that I have to place here but don't know how to do it.
var makeAStep = function() {
if (snake.detectCollision(snake.velocity) === true) {
    var explosion = $('

');
    var newcss = {
        top: parseInt($("#head").css("top").substring(0, $("#head").css("top").length - 2)) - 90 + 'px',
        left: parseInt($("#head").css("left").substring(0, $("#head").css("left").length - 2)) - 61 + 'px',
        position: 'absolute'
    };
    explosion.css(newcss);
    $('#box').append(explosion);
    var alertInterval = setInterval(function() {
        clearInterval(alertInterval);
        $('#explosion').remove();
    }, 800);

    clearInterval(intervalHandler);
    intervalHandler == null;
    return;
}

var lastItemPosition = snake.body[snake.body.length - 1].position.copy();

snake.move();

var iJustAteSomeFood = snake.getHead().isOnPosition(food.position);

if (iJustAteSomeFood == true) {
    food.updateScore();
    generateFood();
    snake.body.push(new snakeItem(lastItemPosition));
}

snake.screenUpdate({updateFireballs: iJustAteSomeFood});

};
The complete code

A: Since you are using jQuery, you can call modal dialog
if (snake.detectCollision(snake.velocity) === true) {
  $("#dialog").dialog("open"); // here
  ...
}

after you create the
...
, see the link example.
Note: Nice game. You should disable 180° rotation, i.e. spaceship moving to the left should not react to right arrow.


text:
Q: commit change of Github downloaded as zip I was working on a project with a friend, however instead of cloning the repo I downloaded it as zip and made several changes. In the mean time the remote one got update by my friend. Now, my code is outdated and I can't commit my changes as github don't recognize the diffences.
I tried cloning into a different location than copied the modified files into the cloned one however, this way I can commit my changes but with the outdated code( not the new changes made by my friend).
Any suggestion would be appreciated ?

A: A zip file is not a Git repository, and cannot be used as one.
A Git repository is, at its heart, really a big collection of commits.  Each commit is like an entire zip file of source files.  So a repository is, in effect, an ever-expanding set of many zip files.
What you can do, to deal with this "correctly"—which may be slightly to very painful, depending on what you did with the original zip file and/or your overall programming ability—is this, which starts with what you did try:

*

*Keep the files you have now somewhere, out of the way.

*Use git clone to make, for yourself, your own Git repository.  This clone will be filled with all the commits that are in the repository you're copying.

*Somehow find the original commit from which you had Git make a zip file.  Create, for your own use, a new branch that selects this commit.

We'll come back to step 3 in a while, but first we should talk more about commits.  The brief one-sentence description above ("like a zip file") is not wrong, but doesn't capture the true essence of a commit.  (If you're impatient and already know all this, scroll to the end.)
What a Git commit is
Each Git commit is:

*

*Numbered.  Every commit anyone ever makes, anywhere, gets a unique number.  To make this work, the numbers are huge, and seemingly random (although they're actually just outputs from a cryptographic hash function).  They're quite useless for humans, but the commit number is how Git finds a commit, so Git needs them.  Git calls these hash IDs, or more formally, object IDs.

*Made up of essentially two parts.  The two parts of a commit are:

*

*all the files, as if in a zip archive (but stored quite differently); and

*some metadata, or information about the commit itself: who made it, when, why (their log message), and so on.

Inside the metadata, Git keeps, for itself, one crucially important piece of information: each commit remembers the raw hash ID of some previous commit.  Actually, it's IDs, plural, of a set of commits, but most commits have just one in here.  Git calls that remembered hash ID the parent commit, and the commit itself is a child of that parent.
Because the hash IDs are cryptographic hashes of the complete contents of each commit, it's impossible to change anything about any commit after it's made.  And, because the hash IDs are unpredictable—they include such things as the time at which the commit is made—it's impossible to include the hash ID of a future commit in any commit we make.  So commits necessarily remember only their parents, never their children.
The result of all this is usually a simple, linear chain of commits:
... <-F <-G <-H

where H stands in for the actual hash ID of our latest commit, whatever that is.  Commit H contains, in its metadata, the raw hash ID of earlier (parent) commit G, so we say that H points to G.  Meanwhile, G is also a commit, so it also has metadata, which contains the raw hash ID of its parent F: G points to F.  F in turn points backwards to some still-earlier commit, and so on.
This is the history in a repository, which is nothing more than the commits in the repository.  All (all?) we have to do is somehow find the latest one: H in the drawing above.  But note that history can diverge:
          I--J   [commits you might make starting from H]
         /
...--G--H
         \
          K--L   [commits your friend makes, also starting with H]

Which of these commits is "the latest"?  The answer is really both: J is your latest, and L is their latest.
This is one form of branching.  Now, it's true that you'll be making your commits in your clone, and your friends will make their commits in their clones, but at some point, someone has to reconcile all these clones.  There are many tools for dealing with this but we won't even start on them here; this is really just to point out the many meanings of the word branch.  This word is badly over-used in Git, but to some extent, we're stuck with it.
A better overview of a Git repository
I already said that a repository as, at its heart, a collection—a database—of commits, and that's true, but again doesn't capture how we'll use this.  In fact, a repository is more like several databases, one of commits and other internal Git objects, plus one other big one and a lot of smaller ones as well.
Since humans are bad at remembering hash IDs, Git gives us an easy way out of this: it provides a names database.  These names include, but are not limited to, what Git calls branch names.  A name, in Git—a branch name, or a tag name, or the things Git calls remote-tracking branch names that I call remote-tracking names (since they're not actually branch names at all)—each name in Git serves the purpose of storing one hash ID.
That's all we need!  One hash ID suffices.  When the name is a branch name, that one hash ID is, by definition, the latest commit "on" that branch:
          I--J   <-- my-feature
         /
...--G--H   <-- main
         \
          K--L   <-- bob-feature

Here, commit H is the latest commit on main.  It's not the latest commit ever: I, J, K and L are all later.  But it's the latest on main, and that's how a Git branch is defined.  Commit J is the latest on my-feature.
The actual set of commits "on" some branch is all the commits we can find by starting at the end and working backwards.  So commits up through H are on all three branches.  If you are used to other version control systems, this idea that commits are on many branches all at the same time may be downright weird.  But that's how Git works.
The other thing about branch names is that they move.  If commits I-J seem right, we can make them be on main now by moving the name main forward along the I-J line:
          I--J   <-- main, my-feature
         /
...--G--H
         \
          K--L   <-- bob-feature

Now all commits up through J are on the two branches, while commits K-L are only on bob-feature.  Or, if this was a mistake, we can force the name main to move back two steps to H again.
So this tells us how we use branch names in a Git repository: they help us—and Git—find commits, by finding whichever commit we want to claim is the latest for that branch.  The commits themselves do not, and cannot, move: they are all set in stone.  (We can change how we draw them: there's no reason we have to put my-feature on the top row, for instance, or we can draw vertically with newer commits higher up, or lower down, or whatever we like.  But the commits themselves are actually immutable.)
Your working tree and the index
If a commit holds a snapshot and is immutable—and it does and is—how are we to get any actual work done?  In fact, the files inside a commit are not only frozen for all time and compressed (as they would be in a zip archive), but are also de-duplicated across the entire repository contents, and are in a form that only Git itself can read.  So, just like any archive, we have to have Git extract the files from a commit before we can use them.
A normal repository therefore provides a work area—which Git calls a working tree or work-tree—where you can do your work.  When we check out a commit, Git fills in this working tree from the files saved in the snapshot.
Since most of what we do with Git involves making new commits—adding more history to the repository—you will now generally modify some of these files, and maybe create new files and/or remove existing files, and then you will want Git to make a new commit from the updated files.  In most version control systems, this is straightforward: you just run their "commit" verb.  Git is not straightforward here.
For various reasons, which you may someday agree with or not, Git now imposes upon you this thing that Git calls, variously, the index, or the staging area, or (rarely these days) the cache.  Why there are three names for this thing is a bit mysterious: I think it's because the original name index is poor, and the name cache is worse.  The name staging area at least reflects how you use it, most of the time.  But it isn't all that descriptive.  My own one-line description for Git's index is that the index holds your proposed next commit.
In other systems, when you use their commit verb, they look at your working tree to see what you've done.  Git, instead, looks at its index.  Whatever files are in Git's index, those are the files that go into the commit.  This means that the index effectively holds copies of the files that will go into the commit.
Git's internal format de-duplicates files.  This is pretty central to making Git efficient: without it, since every commit holds a full copy of every file, your repository would rapidly become obese.  But most commits mostly re-use the previous commits' files.  By storing just one copy, read-only and compressed—eventually super-compressed—Git keeps the storage requirements reasonable.
Meanwhile, what's in Git's index, aka the staging area, is in this compressed and de-duplicated format.  The difference between an index copy of a file and a committed copy is that you can have Git replace the index copy (deleting it, and putting in a different compressed-and-de-duplicated copy instead).  The commit can't be changed, but the index can.
So, when you first check out some commit, making it become the current commit, Git fills in your working tree—but also fills in its index, from that commit.  Now your proposed next commit matches the current commit.
As you modify working-tree copies—which Git doesn't use—they gradually become different from the index copies.  The index copies match the current, or HEAD, commit copies.  At some point though, you're ready to commit some file or files.  At this point you must run git add on the files.1
What git add does is simple, once you know about the index.  It:

*

*reads the working tree copy of the file;

*compresses it and checks for duplicates; and

*updates Git's index appropriately.

If the file is a duplicate, Git tosses out the compressed copy it just made and re-uses the old one instead.  If it's not a duplicate, Git arranges for the file to get stored forever once the commit gets made, and updates the index with that new internal object.  Either way, the index copy now matches the working tree copy, except that the index copy is ready to be committed.  Or, to put it another way: git add updates your proposed next commit.

1You can, if you like, use git commit -a as a shortcut.  If you're new to Git, this is tempting.  Don't do it!  It's a trap!  It lets you avoid thinking about Git's index, but eventually Git will slap you in the face with some surprising aspect of the index.  You need to have Git's index on your mind, even if it's just a sort of background presence.
Still, it's worth mentioning that what git commit -a does is, in effect, turn git commit into git add -u && git commit.  That is, first Git tries to update its index the way git add -u would.  Then, once that succeeds, commit goes on to its normal action.  There's a bunch of tricky stuff here though, having to do with pre-commit hooks and other issues.  It's better to avoid git commit -a as a beginner, and once you're an advanced Git user, you'll often still want to avoid git commit -a for other reasons.

git status, untracked files, and .gitignore
Before we actually simulate a git commit it's worth a brief look at the git status command and what Git calls untracked files.  Untracked files can be "ignored", which is kind of a misnomer.  Tracked files—the files that are not untracked—can't be ignored like this.
Because your working tree is yours, and because it's just an ordinary directory (or folder, if you like that term better) on your computer holding ordinary files, you can do anything you like here without Git knowing what you're doing.
That, plus the fact that you have to run git add on files before Git even bothers to see that you have done anything, makes working with Git painful.  To decrease the pain level, we have git status.  What git status does is simple to describe once you understand what git diff does.  (What git diff does is ... less simple if we were to cover all the details, but for now I'll just assume you know.)
What git status does, in part, is to run two git diff --name-status commands for you.  The first one compares HEAD—the current commit—vs Git's index.  It doesn't show the actual differences, but for any file that is the same, it says nothing at all, and for any file that is different, it says so.
This means that you can instantly tell what files you've changed in Git's index.  Those files are different in your proposed next commit.  If you do commit them now, they will be different in your new commit.
Files that aren't mentioned here must be the same in the current and proposed-next commits ... or, perhaps they're not in HEAD and Git's index at all.  Perhaps they are all new files.  If they are in Git's index, they will show up here as a "new file".  This section of git status output lists these as files to be committed, and each one is either new, modified, or deleted: it's new in the index, or both HEAD and index have the file and they're different, or it's in HEAD but not in the index.
Having gathered up that list for you, git status now goes on to run a second diff.  This time it compares the files that are in Git's index to the files that are in your working tree.  Once again, we can have:

*

*Files that are the same: they're in both, but match.  Git says nothing about these.

*Files that are different: they're in both both but don't match.  Git says these files are not staged for commit.

*Files that have gone missing from the working tree: they're in the index, but not visible to you.  The index contents are not directly observable, but you can view your working tree contents with any ordinary file listing and viewing command, because those are ordinary files.  This particular file isn't there any more, so Git says this file is deleted (but still not staged for commit).

*Files that are all new: they're not in the index, but are in your working tree.

This last group of files has a special status.  These are your untracked files.  Any file that is in your working tree, but is not in Git's index right now, is an untracked file.  The git status command separates out this last listing, of untracked files, from the first two:
$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   worktree.h

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   Makefile
        deleted:    zlib.c

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        newfile.x

Here, I modified worktree.h and ran git add on it.  So the HEAD and index copies are different, and we see that in the Changes to be committed section.
I modified Makefile but didn't git add this, removed zlib.c and didn't git add the removal, and created an all new file newfile.x and didn't git add the file.  So in the section titled Changes not staged for commit, Git lists Makefile as modified, and zlib.c as deleted.  But it doesn't list newfile.x as added here.  Instead, that's down in the Untracked files section.
The untracked files here are separated out primarily for one reason: many things for which we use Git create a lot of untracked files.  We need a mechanism by which we can tell Git two things:

*

*don't complain about this file, and

*if I use an en-masse git add . or similar to just add everything, don't add this file either.

(We haven't really covered the en-masse "add everything" operations but they're very handy, once git status shows the right stuff.  We can add everything, or everything in some particular sub-directory, or whatever.  Git won't add any untracked file that we also told it to shut up about.)
That's a lot of detail to absorb, so let's stop here and move on to the next section.
Making a new commit from Git's index
Once you've arranged Git's index the way you want, so that git status prints what you want it to print—the files you intend to show up, do show up in the to be committed section, and they have what you want them to have in them and don't show up in the not staged for commit section—you can simply run:
git commit

Git will now collect from you all the metadata that needs to go into the new commit that it needs to get from you.  In particular, Git will:

*

*read your user.name and user.email settings to decide what to put into this part;

*use your computer's clock to figure out what time and day it is, for the time-and-date part;

*collect a commit log message from you, typically by opening up an editor on .git/COMMIT_EDITMSG (you can use -m to short-cut this); and

*use the current commit's hash ID as the parent of the new commit.

Git will also turn all the files that are in the index into a new frozen-for-all-time snapshot to put in the new commit, and will then write all of this out as the new commit, which gets a new and unique hash ID.
Now, let's suppose that, at this point, we have this situation:
...--G--H   <-- main, my-feature (HEAD)

That is, we have two existing branch names, main and my-feature, that both select commit H.  We're using the name my-feature.  That means the current commit is commit H.  Git will have filled in our working tree and its index from whatever is in commit H.  Since then, we updated Git's index.
The git commit command has now taken the index contents, frozen them, added the necessary metadata, and written out a new commit, which got some new hash unique hash ID, but we'll just call it "commit I" here:
...--G--H   <-- main
         \
          I   <-- my-feature (HEAD)

The last step of git commit is that it writes I's actual hash ID, whatever that is, into the current branch name.  Since HEAD is attached to the name my-feature, that's the branch name that gets updated.  So now the name my-feature points to commit I.  By definition, our new commit I is now the latest commit on branch my-feature.
Your branch names are yours; remote-tracking names remember theirs
We now come to one other place where Git is a little weird, compared to many other version control systems.  On many systems, a branch name is a very solid thing, that lasts forever, and everyone who clones a repository uses the same branch names everywhere.  That's not the case in Git!  Instead, the branch names in a Git repository are specific to that one repository.
(They have to be, because of that trick where our new commit's hash ID just goes straight into the branch name.  We can only update our repository, not anyone else's, at this time.)
So, when you run git clone to copy some repository to your own laptop, or wherever the clone is going, your Git copies all their commits, but none of their branch names.  Instead of taking their branch names to make yours, your Git takes their branch names and renames them.  Technically they become something that's not a branch name at all: it's a remote-tracking name instead.
If you call the other Git origin—that's the standard name for "the other Git", when there's just the one other Git that you git clone-d from—your Git will take their main and turn it into your origin/main.  Your Git will take their feature and turn it into your origin/feature.  Your Git will turn their branches into your origin/* remote-tracking names.
(Git calls these remote-tracking branch names, as I mentioned before.  But they're not branch names at all.  They're just your Git's way of remembering someone else's branch names.  In that other repository, they don't have origin/ in front of them.  That's why I just call them remote-tracking names: your Git is remembering some other repository's branch names, but not as branch names.)
Having copied all their commits, and turned all their branch names into remote-tracking names, your Git now has one problem: You have no branch names.  What name will your Git use to attach HEAD to?  There isn't any name!
The usual solution to this dilemma is that Git now creates one branch name in your repository.  Which one?  Well, that's what git clone -b is for: you tell your Git which name to create, based on one of their branch names.  If you don't use -b—and most people don't—your Git asks their Git what name they recommend.  That tends to be master or main (depending on who is hosting the Git repository you are cloning).  So they recommend their main, for instance, and your Git now makes your own main from your origin/main, which remembers their main (whew!):
...--G--H   <-- main (HEAD), origin/main

Your Git now checks out this one branch name and all is normal: your current branch name is main and your current commit is whatever commit main selects.  (In this case I've drawn it as hash H as usual.)
If they have other branches, your Git repository might look more like this:
       I--J   <-- origin/feature1
      /
...--G--H   <-- main (HEAD), origin/main
         \
          K   <-- origin/feature2

Each of your remote-tracking names exists to find their latest commit, just as each of their branch names, in their repository, exists to find what is for them the latest commit.
Later, you can run git fetch.  When you do, your Git looks up theirs by name (origin: there's only the one other Git repository involved, so there's just the one standard name for it), calls up the URL listed under the name origin, and asks them what their branch names and latest commit hash IDs are.  If those latest commits match the remote-tracking names in your repository, there's nothing to do.  If not, your Git can get any new commits from them, using the hash IDs.  Now your repository has all of their commits, plus any of your own that you still haven't given to them.  Your Git now updates your remote-tracking names to remember their new latest commits.
We're finally ready to tackle your problem
Let's draw what you did:

*

*Get a zip file, downloading it to your laptop.  This is an archive made from some commit in their repository:
...--G--H   <-- main

Your zip file thus represents commit H.  It's missing the metadata, but it has all the files from the snapshot.

*Extract the zip file.  You now have all the files from commit H, but no Git repository.

*Work on the files.

*Discover the mistake, and clone the repository itself to your laptop.
You now have a repository somewhere on your laptop, plus a folder full of files from commit H, but modified, somewhere else on your laptop.  The repository you have now might look more like this:
...--G--H--I--J--K   <-- main (HEAD), origin/main

What you want to do, for cleanliness purposes, is find which commit is commit H.
You can run git log, which will spill out commits one by one.  If they have branches and merges this gets complicated, and you should read through Pretty Git branch graphs, but if not, you can maybe just search by date or something, to find commit H.  The actual hash IDs will be large, ugly, and random-looking, so they won't help any.  (To use them, you probably want to cut-and-paste with your mouse: it's really error-prone to try to type one in!)
There's a possible short-cut.  If you still have the original zip file, look at its metadata.  There is a file comment holding the actual hash ID.  Grab it (with mouse or whatever) and you're golden!  If not, how you find the right hash—the one I'm calling H here—is up to you.  Another trick you can use is this: git diff can compare any commit to any file-tree, even one that's outside the Git repository.  With git log, you get hash IDs; you can run:
git diff <hash> /path/to/unzipped/files

and get a diff listing.  If the only changes you see are your changes, the hash here is probably H.  You can use git log's dates to get a short-list of candidates for this kind of git diff, and then use trial-and-error to find the closest commit.
Assuming you have found hash ID H, all you have to do now is create a new branch name that points directly to this hash ID.  To do that, use the git branch command:
git branch branch-xyzzy <hash>

(pick a better branch name, and use the mouse again for the cut-and-paste of hash IDs).  Now you have, in your repository:
...--G--H   <-- branch-xyzzy
         \
          I--J--K   <-- main (HEAD), origin/main

You can now run git checkout branch-xyzzy:
...--G--H   <-- branch-xyzzy (HEAD)
         \
          I--J--K   <-- main, origin/main

The files in your working tree are now those from commit H.  Copy the files in from the place you worked on the zip archive, use git diff and/or git status to figure out what to git add or just git add . and run git status, and you're ready to commit!  Your new commit will get a new, unique hash ID, and the name branch-xyzzy will point to it:
...--G--H--L   <-- branch-xyzzy (HEAD)
         \
          I--J--K   <-- main, origin/main

or, equivalently:
...--G--H--I--J--K   <-- main, origin/main
         \
          L   <-- branch-xyzzy (HEAD)

Note how we can re-draw the drawing without actually changing any commits.  Get used to the fact that graph drawings morph a lot: whatever graph-drawing software you use, such as the stuff built in to GitKraken—you tagged your question with gitkraken—will have its own preferences.  They may or may not match up with yours.  The important things are the arrows from commits to earlier commits, and the various names that point to particular commits.  The arrows from commit to commit can't change, because no part of any commit can change, but the arrows from names can.
We make use of the last bit a lot.  For instance, now that you have:
...--G--H--I--J--K   <-- main, origin/main
         \
          L   <-- branch-xyzzy (HEAD)

you might want to use git rebase.  This copies commits, to new and improved ones.  Commit L might be fine, but it might be better if it built on commit K.  You can't actually do that, but you can make a new and improved commit—let's call it L'—that does do that:
                   L'  <-- improved-branch-xyzzy
                  /
...--G--H--I--J--K   <-- main, origin/main
         \
          L   <-- old-branch-xyzzy

If we now delete the old name, making commit L hard to find, and use the name over again to point to L' instead of L:
                   L'  <-- branch-xyzzy (HEAD)
                  /
...--G--H--I--J--K   <-- main, origin/main
         \
          L   ???

and then use any commit viewer to look at the commits, it will seem as though we changed commit L.  The new copy, L', has a different hash ID, and points backwards to K, but makes the same changes that H-vs-L would show.  It has the same commit message that L had.  So if we don't remember the hash ID—and nobody ever does—we might not even know this happened!

A: No need to overcomplicate. Any folder can be a git repo, as long as it has the .git folder. I did the following:

*

*clone the Github repo to another location

*copy the .git folder to your downloaded zip folder using the command line (mv .git/ ~/new-location/.git/)

Now create a new branch, commit everything, merge in main/master and fix all conflicts. Then commit again and you're done.


text:
Q: Display id value Could someone help me out, I'm trying to display the values to what these id's are linked to.
here is a part from my html

and here is my j query
var details = {what:'fun and games',
               when:'Thursday',
               where:'Jeffs House'}

So basically I want the values  ^^ here to be displayed.
thanks

A: Well, you could loop through the properties of this object and set the corresponding values:
var performance = {
    what: 'fun and games',
    when: 'Thursday',
    where: 'Jeffs House'
};

for (var key in performance) {
    if (performance.hasOwnProperty(key)) {
        $('#' + key).html(performance[key]);
    }
}

And here's a live demo.


text:
Q: Create Wizard for visual Studio Item Template Im Using visual studio item templates .
as I see before mvc has an wizard that let you choose some options for you view and
I know thats a template
so any one know how to add wizards with custom code behind for item templates??
any reference and link can help me to improve my project


text:
Q: How to create notifications while app is minimized in android? I have been working on this code using the NotificationManager class to make a notification.
However, I want to display notifications even when the app is in background. Any ideas?
  @Override
  protected void onPostExecute(String result) {
      try
      {
           Thread t=new Thread()
          {
            public void run()
            {
                try
                {

                        JSONObject jsonResponse = new JSONObject(jsonResult);
                        JSONArray jsonMainNode = jsonResponse.optJSONArray("user");
                        for (int i = 0; i < jsonMainNode.length(); i++)
                        {
                            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                            String name = jsonChildNode.optString("userid");
                            String number = jsonChildNode.optString("unreadmesage");
                            Thread.sleep(5000);
                            NotificationManager nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
                            Notification n=new Notification(R.drawable.mainicon,"New Msg From ASKCOTTON",System.currentTimeMillis());
                            //n.defaults=n.FLAG_ONLY_ALERT_ONCE+Notification.FLAG_AUTO_CANCEL;
                            Intent in=new Intent(getApplicationContext(),message.class);
                            PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, in, 0);
                           // n.flags |= Notification.FLAG_ONGOING_EVENT;
                            n.setLatestEventInfo(getBaseContext(), "ASKCOTTON", "You Have New Message(s)", pi);
                            nm.notify(1,n);
                        }
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
          };t.start();

      }catch(Exception e)
      {

      }
  }

A: You have to build a Service class.
The Service will run in background even if your application is minimized.
It will build your notifications and send them through the NotificationManager.
Take a look at this link: http://it-ride.blogspot.it/2010/10/android-implementing-notification.html